package main

import (
	"connectx"
	"fmt"
	"google.golang.org/protobuf/compiler/protogen"
	"google.golang.org/protobuf/types/pluginpb"
	"os"
	"path"
	"path/filepath"
	"strings"
)

func main() {
	if len(os.Args) == 2 && os.Args[1] == "--version" {
		fmt.Fprintln(os.Stdout, connectx.Version)
		os.Exit(0)
	}
	protogen.Options{}.Run(
		func(plugin *protogen.Plugin) error {
			plugin.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)

			// 跟踪已生成的全局定义，避免重复生成
			generatedGlobals := make(map[string]bool)
			// 跟踪每个包是否已生成通用文件
			generatedCommFiles := make(map[string]bool)

			for _, file := range plugin.Files {
				if !file.Generate {
					continue
				}
				// 只有当文件包含服务定义时才生成补充文件
				if len(file.Services) == 0 {
					continue
				}
				generatedFilenamePrefixToSlash := filepath.ToSlash(file.GeneratedFilenamePrefix)
				file.GeneratedFilenamePrefix = path.Join(
					path.Dir(generatedFilenamePrefixToSlash),
					string(file.GoPackageName),
					path.Base(generatedFilenamePrefixToSlash),
				)

				// 为每个包生成通用文件（只生成一次）
				packageKey := file.GoImportPath.String()
				if !generatedCommFiles[packageKey] {
					GenerateCommFile(plugin, file)
					generatedCommFiles[packageKey] = true
				}

				generateFile(plugin, file, generatedGlobals)
			}
			return nil
		},
	)
}

func generateFile(plugin *protogen.Plugin, file *protogen.File, generatedGlobals map[string]bool) {
	generatedFile := plugin.NewGeneratedFile(
		file.GeneratedFilenamePrefix+connectx.GeneratedFilenameExtension,
		file.GoImportPath,
	)
	// 确保目标目录存在
	if err := os.MkdirAll(path.Dir(file.GeneratedFilenamePrefix), 0755); err != nil {
		plugin.Error(err)
		return
	}

	for _, service := range file.Services {
		connectx.ChangeServiceName(service)
	}
	generatedFile.P("package ", file.GoPackageName)
	generatedFile.P()
	generatedFile.P("import (")
	generatedFile.P(`"encoding/json"`)
	generatedFile.P(`"errors"`)
	generatedFile.P(`"gitee.com/filters/utils/logv"`)
	generatedFile.P(`"github.com/rs/zerolog/log"`)
	generatedFile.P(`"reflect"`)
	generatedFile.P(`"strings"`)
	generatedFile.P(`"time"`)
	//generatedFile.P(`"crypto/rand"`)
	//generatedFile.P(`"encoding/hex"`)
	generatedFile.P(connectx.ProtoreflectPackage)
	generatedFile.P(connectx.ContextPackage)
	generatedFile.P(connectx.FmtPackage)
	generatedFile.P(connectx.HttpPackage)
	//generatedFile.P(connectx.LogPackage)

	generatedFile.P(`"google.golang.org/protobuf/types/descriptorpb"`)
	generatedFile.P(`"google.golang.org/protobuf/encoding/protojson"`)
	generatedFile.P(")")
	generatedFile.P()
	//常量 - 传入 generatedGlobals 来避免重复生成
	generatedConstants(generatedFile, file, generatedGlobals)
	generatedServer(generatedFile, file, generatedGlobals)
}

func generatedServer(g *protogen.GeneratedFile, file *protogen.File, generatedGlobals map[string]bool) {
	// 为每个服务生成所有相关代码
	for _, service := range file.Services {
		generateServiceDescriptors(g, service, file)
		generateConnectServiceClient(g, service)
		generateConnectServiceHandler(g, service)
		generateServiceServerInterface(g, service)
		generateServiceAdapter(g, service)
		generateHandlerWithMethodConfig(g, service)
		generateHandlerWithHTTPMethods(g, service)
		generateUnifiedMethodHandler(g, service)
		generateServiceChainMethod(g, service)
	}
}

// generateServiceDescriptors 生成服务描述符相关代码
func generateServiceDescriptors(g *protogen.GeneratedFile, service *protogen.Service, file *protogen.File) {
	serviceName := service.GoName
	serviceNameLower := strings.ToLower(serviceName)

	// 生成全局变量
	g.P("// 公共服务描述符，使用延迟初始化避免包初始化顺序问题")
	g.P("var (")
	g.P(serviceNameLower, "ServiceDescriptor     protoreflect.ServiceDescriptor")
	for _, method := range service.Methods {
		//methodNameLower := strings.ToLower(method.GoName)
		g.P(serviceNameLower, "Service", method.GoName, "MethodDescriptor protoreflect.MethodDescriptor")
	}
	g.P(serviceNameLower, "ServiceDescriptorsInitialized            bool")
	g.P(")")
	g.P()

	// 生成初始化函数
	g.P("// init", serviceName, "ServiceDescriptors 初始化", serviceName, "服务描述符（延迟初始化）")
	g.P("func init", serviceName, "ServiceDescriptors() {")
	g.P("if !", serviceNameLower, "ServiceDescriptorsInitialized {")
	g.P(serviceNameLower, "ServiceDescriptor = File_", strings.ToLower(strings.ReplaceAll(file.Proto.GetName(), ".proto", "_proto")), ".Services().ByName(\"", serviceName, "\")")
	for _, method := range service.Methods {
		//methodNameLower := strings.ToLower(method.GoName)
		g.P(serviceNameLower, "Service", method.GoName, "MethodDescriptor = ", serviceNameLower, "ServiceDescriptor.Methods().ByName(\"", method.GoName, "\")")
	}
	g.P(serviceNameLower, "ServiceDescriptorsInitialized = true")
	g.P("}")
	g.P("}")
	g.P()

	// 生成公共获取函数
	g.P("// Get", serviceName, "ServiceDescriptor 获取", serviceName, "服务描述符")
	g.P("func Get", serviceName, "ServiceDescriptor() protoreflect.ServiceDescriptor {")
	g.P("init", serviceName, "ServiceDescriptors()")
	g.P("return ", serviceNameLower, "ServiceDescriptor")
	g.P("}")
	g.P()

	for _, method := range service.Methods {
		g.P("// Get", serviceName, method.GoName, "MethodDescriptor 获取", serviceName, method.GoName, "方法描述符")
		g.P("func Get", serviceName, method.GoName, "MethodDescriptor() protoreflect.MethodDescriptor {")
		g.P("init", serviceName, "ServiceDescriptors()")
		g.P("return ", serviceNameLower, "Service", method.GoName, "MethodDescriptor")
		g.P("}")
		g.P()
	}

	// 生成字段注解获取函数
	g.P("// Get", serviceName, "FieldAnnotations 获取", serviceName, "服务字段注解信息")
	g.P("func Get", serviceName, "FieldAnnotations() map[string]map[string]string {")
	g.P("annotations := make(map[string]map[string]string)")
	g.P("serviceDesc := Get", serviceName, "ServiceDescriptor()")
	g.P()

	for _, method := range service.Methods {
		// 处理输入消息的字段注解
		g.P("// ", method.GoName, " 输入消息字段注解")
		g.P("if inputDesc := serviceDesc.Methods().ByName(\"", method.GoName, "\").Input(); inputDesc != nil {")
		g.P("inputAnnotations := make(map[string]string)")
		g.P("inputFields := inputDesc.Fields()")
		g.P("for i := 0; i < inputFields.Len(); i++ {")
		g.P("field := inputFields.Get(i)")
		g.P("if options := field.Options().(*descriptorpb.FieldOptions); options != nil {")
		g.P("// 这里可以根据需要提取特定的注解")
		g.P("inputAnnotations[string(field.Name())] = fmt.Sprintf(\"字段: %s, 类型: %s\", field.Name(), field.Kind().String())")
		g.P("} else {")
		g.P("inputAnnotations[string(field.Name())] = fmt.Sprintf(\"字段: %s, 类型: %s\", field.Name(), field.Kind().String())")
		g.P("}")
		g.P("}")
		g.P("annotations[\"", method.GoName, "Request\"] = inputAnnotations")
		g.P("}")
		g.P()

		// 处理输出消息的字段注解
		g.P("// ", method.GoName, " 输出消息字段注解")
		g.P("if outputDesc := serviceDesc.Methods().ByName(\"", method.GoName, "\").Output(); outputDesc != nil {")
		g.P("outputAnnotations := make(map[string]string)")
		g.P("outputFields := outputDesc.Fields()")
		g.P("for i := 0; i < outputFields.Len(); i++ {")
		g.P("field := outputFields.Get(i)")
		g.P("if options := field.Options().(*descriptorpb.FieldOptions); options != nil {")
		g.P("outputAnnotations[string(field.Name())] = fmt.Sprintf(\"字段: %s, 类型: %s\", field.Name(), field.Kind().String())")
		g.P("} else {")
		g.P("outputAnnotations[string(field.Name())] = fmt.Sprintf(\"字段: %s, 类型: %s\", field.Name(), field.Kind().String())")
		g.P("}")
		g.P("}")
		g.P("annotations[\"", method.GoName, "Response\"] = outputAnnotations")
		g.P("}")
		g.P()
	}

	g.P("return annotations")
	g.P("}")
	g.P()

	// 生成打印字段注解的函数
	g.P("// Print", serviceName, "FieldAnnotations 打印", serviceName, "服务字段注解信息")
	g.P("func Print", serviceName, "FieldAnnotations() {")
	g.P("annotations := Get", serviceName, "FieldAnnotations()")
	g.P("fmt.Println(\"\\n📝 ", serviceName, " 服务字段注解信息:\")")
	g.P("fmt.Println(strings.Repeat(\"=\", 50))")
	g.P("for msgType, fields := range annotations {")
	g.P("fmt.Printf(\"\\n📋 消息类型: %s\\n\", msgType)")
	g.P("for fieldName, annotation := range fields {")
	g.P("fmt.Printf(\"  🔸 %s: %s\\n\", fieldName, annotation)")
	g.P("}")
	g.P("}")
	g.P("fmt.Println(strings.Repeat(\"=\", 50))")
	g.P("}")
	g.P()

	// 生成内部使用的获取函数
	g.P("// get", serviceName, "ServiceDescriptor 内部使用的获取服务描述符函数")
	g.P("func get", serviceName, "ServiceDescriptor() protoreflect.ServiceDescriptor {")
	g.P("init", serviceName, "ServiceDescriptors()")
	g.P("return ", serviceNameLower, "ServiceDescriptor")
	g.P("}")
	g.P()

	for _, method := range service.Methods {
		//methodNameLower := strings.ToLower(method.GoName[:1]) + method.GoName[1:]
		g.P("// get", serviceName, method.GoName, "MethodDescriptor 内部使用的获取", serviceName, method.GoName, "方法描述符函数")
		g.P("func get", serviceName, method.GoName, "MethodDescriptor() protoreflect.MethodDescriptor {")
		g.P("init", serviceName, "ServiceDescriptors()")
		g.P("return ", serviceNameLower, "Service", method.GoName, "MethodDescriptor")
		g.P("}")
		g.P()
	}
}

// generateConnectServiceClient 生成Connect服务客户端构造函数
func generateConnectServiceClient(g *protogen.GeneratedFile, service *protogen.Service) {
	serviceName := service.GoName
	clientStructName := strings.ToLower(serviceName[:1]) + serviceName[1:] + "Client"

	g.P("func New", serviceName, "ConnectxServiceClient(httpClient ", connectx.ConnectPackage.Ident("HTTPClient"), ", baseURL string, opts ...", connectx.ConnectPackage.Ident("ClientOption"), ") ", serviceName, "Client {")
	g.P("baseURL = strings.TrimRight(baseURL, \"/\")")
	g.P("return &", clientStructName, "{")

	for _, method := range service.Methods {
		methodName := strings.ToLower(method.GoName[:1]) + method.GoName[1:]
		procedureName := serviceName + method.GoName + "Procedure"
		requestType := method.Input.GoIdent.GoName
		responseType := method.Output.GoIdent.GoName

		g.P(methodName, ": ", connectx.ConnectPackage.Ident("NewClient"), "[", requestType, ", ", responseType, "](")
		g.P("httpClient,")
		g.P("baseURL+", procedureName, ",")
		g.P(connectx.ConnectPackage.Ident("WithSchema"), "(Get", serviceName, method.GoName, "MethodDescriptor()),")
		g.P(connectx.ConnectPackage.Ident("WithClientOptions"), "(opts...),")
		g.P("),")
	}

	g.P("}")
	g.P("}")
	g.P()
}

// generateConnectServiceHandler 生成Connect服务处理器
func generateConnectServiceHandler(g *protogen.GeneratedFile, service *protogen.Service) {
	serviceName := service.GoName

	g.P("// grcp转成http请求handler")
	g.P("func New", serviceName, "ConnectxServiceHandler(svc ", serviceName, "Handler, opts ...", connectx.ConnectPackage.Ident("HandlerOption"), ") (string, http.Handler) {")

	// 为每个方法生成处理器
	for _, method := range service.Methods {
		methodNameLower := strings.ToLower(method.GoName[:1]) + method.GoName[1:]
		procedureName := serviceName + method.GoName + "Procedure"
		g.P(methodNameLower, "_ServerHandlerTemp := ", connectx.ConnectPackage.Ident("NewUnaryHandler"), "(")
		g.P(procedureName, ",")
		g.P("svc.", method.GoName, ",")
		g.P(connectx.ConnectPackage.Ident("WithSchema"), "(Get", serviceName, method.GoName, "MethodDescriptor()),")
		g.P(connectx.ConnectPackage.Ident("WithHandlerOptions"), "(opts...),")
		g.P(")")
	}

	g.P("return ", serviceName, "Name, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {")
	g.P("// 默认只支持POST方法")
	g.P("if r.Method != ", connectx.HTTPMethodPOST, " {")
	g.P("http.Error(w, \"Method not allowed. Only POST is supported by default.\", http.StatusMethodNotAllowed)")
	g.P("return")
	g.P("}")
	g.P("switch r.URL.Path {")

	for _, method := range service.Methods {
		methodNameLower := strings.ToLower(method.GoName[:1]) + method.GoName[1:]
		procedureName := serviceName + method.GoName + "Procedure"
		g.P("case ", procedureName, ":")
		g.P(methodNameLower, "_ServerHandlerTemp.ServeHTTP(w, r)")
	}

	g.P("default:")
	g.P("http.NotFound(w, r)")
	g.P("}")
	g.P("})")
	g.P("}")
	g.P()
}

// generateServiceServerInterface 生成服务器接口
func generateServiceServerInterface(g *protogen.GeneratedFile, service *protogen.Service) {
	serviceName := service.GoName

	g.P("// ", serviceName, "Server is the standard gRPC server interface.")
	g.P("type ", serviceName, "Server interface {")
	for _, method := range service.Methods {
		requestType := method.Input.GoIdent.GoName
		responseType := method.Output.GoIdent.GoName
		g.P(method.GoName, "(context.Context, *", requestType, ") (*", responseType, ", error)")
	}
	g.P("}")
	g.P()

	// 生成接口实现检查函数
	g.P("// Validate", serviceName, "ServerImplementation 检查服务器是否完全实现了", serviceName, "Server接口")
	g.P("func Validate", serviceName, "ServerImplementation(server ", serviceName, "Server) error {")
	g.P("if server == nil {")
	g.P("return fmt.Errorf(\"", serviceName, "Server 不能为 nil\")")
	g.P("}")
	g.P()

	// 使用反射检查每个方法是否实现
	g.P("// 使用类型断言检查接口实现")
	g.P("serverType := reflect.TypeOf(server)")
	g.P("interfaceType := reflect.TypeOf((*", serviceName, "Server)(nil)).Elem()")
	g.P()
	g.P("// 检查是否实现了接口")
	g.P("if !serverType.Implements(interfaceType) {")
	g.P("return fmt.Errorf(\"类型 %s 没有完全实现 ", serviceName, "Server 接口\", serverType)")
	g.P("}")
	g.P()

	// 详细检查每个方法
	g.P("// 详细检查每个方法的实现")
	g.P("missingMethods := []string{}")
	for _, method := range service.Methods {
		g.P("if method, ok := serverType.MethodByName(\"", method.GoName, "\"); !ok {")
		g.P("missingMethods = append(missingMethods, \"", method.GoName, "\")")
		g.P("} else {")
		g.P("// 检查方法签名")
		g.P("methodType := method.Type")
		g.P("if methodType.NumIn() != 3 || methodType.NumOut() != 2 {")
		g.P("missingMethods = append(missingMethods, \"", method.GoName, " (签名不正确)\")")
		g.P("}")
		g.P("}")
	}
	g.P()
	g.P("if len(missingMethods) > 0 {")
	g.P("return fmt.Errorf(\"", serviceName, "Server 缺少以下方法实现: %v\", missingMethods)")
	g.P("}")
	g.P()
	g.P("fmt.Printf(\"✅ ", serviceName, "Server 接口实现检查通过\\n\")")
	g.P("return nil")
	g.P("}")
	g.P()
}

// generateServiceAdapter 生成服务适配器
func generateServiceAdapter(g *protogen.GeneratedFile, service *protogen.Service) {
	serviceName := service.GoName
	serviceNameLower := strings.ToLower(serviceName[:1]) + serviceName[1:]
	adapterName := serviceNameLower + "ServiceServiceAdapter"

	g.P("type ", adapterName, " struct {")
	g.P("server       ", serviceName, "Server")
	g.P("interceptors []Interceptor")
	g.P("}")
	g.P()

	g.P("func New", serviceName, "ServiceAdapter(server ", serviceName, "Server) ", serviceName, "Handler {")
	g.P("return &", adapterName, "{server: server, interceptors: []Interceptor{}}")
	g.P("}")
	g.P()

	g.P("func New", serviceName, "ServiceAdapterWithInterceptors(server ", serviceName, "Server, interceptors ...Interceptor) ", serviceName, "Handler {")
	g.P("return &", adapterName, "{server: server, interceptors: interceptors}")
	g.P("}")
	g.P()

	g.P("func (a *", adapterName, ") runInterceptors(ctx context.Context, method string, req interface{}) (context.Context, error) {")
	g.P("for _, interceptor := range a.interceptors {")
	g.P("var err error")
	g.P("ctx, err = interceptor.Intercept(ctx, method, req)")
	g.P("if err != nil {")
	g.P("return ctx, err")
	g.P("}")
	g.P("}")
	g.P("return ctx, nil")
	g.P("}")
	g.P()

	g.P("func (a *", adapterName, ") extractHeadersFromConnect(ctx context.Context, req interface{}) context.Context {")
	g.P("switch r := req.(type) {")
	for _, method := range service.Methods {
		requestType := method.Input.GoIdent.GoName
		g.P("case *", connectx.ConnectPackage.Ident("Request"), "[", requestType, "]:")
		g.P("headers := make(map[string][]string)")
		g.P("for key, values := range r.Header() {")
		g.P("headers[strings.ToLower(key)] = values")
		g.P("}")
		g.P("return context.WithValue(ctx, \"headers\", headers)")
	}
	g.P("}")
	g.P("return ctx")
	g.P("}")
	g.P()

	// 为每个方法生成适配器方法
	for _, method := range service.Methods {
		requestType := method.Input.GoIdent.GoName
		responseType := method.Output.GoIdent.GoName

		g.P("func (a *", adapterName, ") ", method.GoName, "(ctx context.Context, req *", connectx.ConnectPackage.Ident("Request"), "[", requestType, "]) (*", connectx.ConnectPackage.Ident("Response"), "[", responseType, "], error) {")
		g.P("ctx = a.extractHeadersFromConnect(ctx, req)")
		g.P("var err error")
		g.P("ctx, err = a.runInterceptors(ctx, \"", method.GoName, "\", req)")
		g.P("if err != nil {")
		g.P("return nil, err")
		g.P("}")
		g.P("grpcReq := req.Msg")
		g.P("grpcResp, err := a.server.", method.GoName, "(ctx, grpcReq)")
		g.P("if err != nil {")
		g.P("return nil, err")
		g.P("}")
		g.P("connectResp := ", connectx.ConnectPackage.Ident("NewResponse"), "(grpcResp)")
		g.P("return connectResp, nil")
		g.P("}")
		g.P()
	}
}

// generateHandlerWithMethodConfig 生成支持方法配置的处理器
func generateHandlerWithMethodConfig(g *protogen.GeneratedFile, service *protogen.Service) {
	serviceName := service.GoName

	g.P("// New", serviceName, "HandlerWithMethodConfig 创建支持指定方法和HTTP方法的处理器")
	g.P("// 直接调用标准gRPC方法，HTTP和gRPC走同一套逻辑")
	g.P("func New", serviceName, "HandlerWithMethodConfig(server ", serviceName, "Server, interceptors []Interceptor, methodConfigs []MethodHTTPConfig, opts ...", connectx.ConnectPackage.Ident("HandlerOption"), ") (string, http.Handler) {")
	g.P("// 构建方法配置映射")
	g.P("methodConfigMap := make(map[string]map[string]bool)")
	g.P("for _, config := range methodConfigs {")
	g.P("methodConfigMap[config.MethodName] = make(map[string]bool)")
	g.P("for _, method := range config.AllowedMethods {")
	g.P("methodConfigMap[config.MethodName][method] = true")
	g.P("}")
	g.P("}")
	g.P()

	g.P("// 创建统一的方法处理器")
	g.P("unifiedHandler := NewUnified", serviceName, "MethodHandler(server, interceptors)")
	g.P()

	g.P("return ", serviceName, "Name, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {")
	g.P("// 根据路径确定方法名")
	g.P("var methodName string")
	g.P("switch r.URL.Path {")

	for _, method := range service.Methods {
		procedureName := serviceName + method.GoName + "Procedure"
		g.P("case ", procedureName, ":")
		g.P("methodName = \"", method.GoName, "\"")
	}

	g.P("default:")
	g.P("http.NotFound(w, r)")
	g.P("return")
	g.P("}")
	g.P()

	g.P("// 检查该方法是否支持当前HTTP方法")
	g.P("if allowedMethods, exists := methodConfigMap[methodName]; exists {")
	g.P("if !allowedMethods[r.Method] {")
	g.P("allowedList := GetKeys(allowedMethods)")
	g.P("http.Error(w, fmt.Sprintf(\"Method %s not allowed for %s. Allowed methods: %v\",")
	g.P("r.Method, methodName, allowedList), http.StatusMethodNotAllowed)")
	g.P("return")
	g.P("}")
	g.P("} else {")
	g.P("// 如果没有配置，默认只支持POST")
	g.P("if r.Method != ", connectx.HTTPMethodPOST, " {")
	g.P("http.Error(w, fmt.Sprintf(\"Method %s not allowed for %s. Only POST is supported by default.\",")
	g.P("r.Method, methodName), http.StatusMethodNotAllowed)")
	g.P("return")
	g.P("}")
	g.P("}")
	g.P()

	g.P("// 直接调用统一的方法处理器")
	g.P("unifiedHandler.HandleRequest(w, r, methodName)")
	g.P("})")
	g.P("}")
	g.P()
}

// generateHandlerWithHTTPMethods 生成支持HTTP方法的处理器
func generateHandlerWithHTTPMethods(g *protogen.GeneratedFile, service *protogen.Service) {
	serviceName := service.GoName
	serviceNameLower := strings.ToLower(serviceName[:1]) + serviceName[1:]
	adapterName := serviceNameLower + "ServiceAdapter"

	g.P("// ", adapterName, " adapts a standard gRPC server to the Connect handler interface.")
	g.P("type ", adapterName, " struct {")
	g.P("server       ", serviceName, "Server")
	g.P("interceptors []Interceptor")
	g.P("}")
	g.P()

	g.P("// New", serviceName, "Adapter creates an adapter that converts standard gRPC methods to Connect handlers.")
	g.P("func New", serviceName, "Adapter(server ", serviceName, "Server) ", serviceName, "Handler {")
	g.P("return &", adapterName, "{server: server, interceptors: []Interceptor{}}")
	g.P("}")
	g.P()

	g.P("// New", serviceName, "AdapterWithInterceptors creates an adapter with interceptors.")
	g.P("func New", serviceName, "AdapterWithInterceptors(server ", serviceName, "Server, interceptors ...Interceptor) ", serviceName, "Handler {")
	g.P("return &", adapterName, "{server: server, interceptors: interceptors}")
	g.P("}")
	g.P()

	g.P("// runInterceptors executes all interceptors in order.")
	g.P("func (a *", adapterName, ") runInterceptors(ctx context.Context, method string, req interface{}) (context.Context, error) {")
	g.P("for _, interceptor := range a.interceptors {")
	g.P("var err error")
	g.P("ctx, err = interceptor.Intercept(ctx, method, req)")
	g.P("if err != nil {")
	g.P("return ctx, err")
	g.P("}")
	g.P("}")
	g.P("return ctx, nil")
	g.P("}")
	g.P()

	g.P("// extractHeadersFromConnect extracts headers from Connect request and adds them to context.")
	g.P("func (a *", adapterName, ") extractHeadersFromConnect(ctx context.Context, req interface{}) context.Context {")
	g.P("// Try to extract headers from Connect request")
	g.P("switch r := req.(type) {")
	for _, method := range service.Methods {
		requestType := method.Input.GoIdent.GoName
		g.P("case *", connectx.ConnectPackage.Ident("Request"), "[", requestType, "]:")
		g.P("headers := make(map[string][]string)")
		g.P("for key, values := range r.Header() {")
		g.P("headers[strings.ToLower(key)] = values")
		g.P("}")
		g.P("return context.WithValue(ctx, \"headers\", headers)")
	}
	g.P("}")
	g.P("return ctx")
	g.P("}")
	g.P()

	// 为每个方法生成适配器方法
	for _, method := range service.Methods {
		requestType := method.Input.GoIdent.GoName
		responseType := method.Output.GoIdent.GoName

		g.P("// ", method.GoName, " adapts the standard gRPC ", method.GoName, " method to Connect format.")
		g.P("func (a *", adapterName, ") ", method.GoName, "(ctx context.Context, req *", connectx.ConnectPackage.Ident("Request"), "[", requestType, "]) (*", connectx.ConnectPackage.Ident("Response"), "[", responseType, "], error) {")
		g.P("// Extract headers and add to context for interceptors")
		g.P("ctx = a.extractHeadersFromConnect(ctx, req)")
		g.P()
		g.P("// Run interceptors")
		g.P("var err error")
		g.P("ctx, err = a.runInterceptors(ctx, \"", method.GoName, "\", req)")
		g.P("if err != nil {")
		g.P("return nil, err")
		g.P("}")
		g.P()
		g.P("// Convert Connect request to standard gRPC request")
		g.P("grpcReq := req.Msg")
		g.P()
		g.P("// Call the standard gRPC method")
		g.P("grpcResp, err := a.server.", method.GoName, "(ctx, grpcReq)")
		g.P("if err != nil {")
		g.P("return nil, err")
		g.P("}")
		g.P()
		g.P("// Convert standard gRPC response to Connect response")
		g.P("connectResp := ", connectx.ConnectPackage.Ident("NewResponse"), "(grpcResp)")
		g.P("return connectResp, nil")
		g.P("}")
		g.P()
	}

	// 生成HTTP方法处理器
	g.P("// New", serviceName, "HandlerWithHTTPMethods 创建支持多种HTTP方法的处理器")
	g.P("func New", serviceName, "HandlerWithHTTPMethods(svc ", serviceName, "Handler, opts ...", connectx.ConnectPackage.Ident("HandlerOption"), ") (string, http.Handler) {")
	g.P("// 获取原始的Connect处理器")
	g.P("basePath, baseHandler := New", serviceName, "Handler(svc, opts...)")
	g.P()
	g.P("// 创建HTTP方法处理器")
	g.P("methodHandler := NewDefaultHTTPMethodHandler(baseHandler)")
	g.P()
	g.P("return basePath, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {")
	g.P("// 记录请求信息")
	g.P("log.Printf(\"HTTP %s request to %s\", r.Method, r.URL.Path)")
	g.P()
	g.P("// 根据HTTP方法分发请求")
	g.P("switch r.Method {")
	g.P("case ", connectx.HTTPMethodGET, ":")
	g.P("if err := methodHandler.HandleGET(w, r, r.URL.Path); err != nil {")
	g.P("log.Printf(\"GET request error: %v\", err)")
	g.P("}")
	g.P("case ", connectx.HTTPMethodPOST, ":")
	g.P("if err := methodHandler.HandlePOST(w, r, r.URL.Path); err != nil {")
	g.P("log.Printf(\"POST request error: %v\", err)")
	g.P("}")
	g.P("case ", connectx.HTTPMethodDELETE, ":")
	g.P("if err := methodHandler.HandleDELETE(w, r, r.URL.Path); err != nil {")
	g.P("log.Printf(\"DELETE request error: %v\", err)")
	g.P("}")
	g.P("case ", connectx.HTTPMethodPUT, ":")
	g.P("if err := methodHandler.HandlePUT(w, r, r.URL.Path); err != nil {")
	g.P("log.Printf(\"PUT request error: %v\", err)")
	g.P("}")
	g.P("case ", connectx.HTTPMethodOPTIONS, ":")
	g.P("// 处理CORS预检请求")
	g.P("w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")")
	g.P("w.Header().Set(\"Access-Control-Allow-Methods\", ", connectx.HTTPMethodGET, "+\", \"+", connectx.HTTPMethodPOST, "+\", \"+", connectx.HTTPMethodPUT, "+\", \"+", connectx.HTTPMethodDELETE, "+\", \"+", connectx.HTTPMethodOPTIONS, ")")
	g.P("w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization, x-token\")")
	g.P("w.WriteHeader(http.StatusOK)")
	g.P("default:")
	g.P("http.Error(w, \"Method not allowed\", http.StatusMethodNotAllowed)")
	g.P("}")
	g.P("})")
	g.P("}")
	g.P()

	// 生成自定义HTTP方法处理器
	g.P("// New", serviceName, "HandlerWithCustomHTTPMethods 创建自定义HTTP方法支持的处理器")
	g.P("func New", serviceName, "HandlerWithCustomHTTPMethods(svc ", serviceName, "Handler, config *HTTPMethodConfig, opts ...", connectx.ConnectPackage.Ident("HandlerOption"), ") (string, http.Handler) {")
	g.P("if config == nil {")
	g.P("config = DefaultHTTPMethodConfig()")
	g.P("}")
	g.P()
	g.P("// 获取原始的Connect处理器")
	g.P("basePath, baseHandler := New", serviceName, "Handler(svc, opts...)")
	g.P()
	g.P("// 创建HTTP方法处理器")
	g.P("methodHandler := NewDefaultHTTPMethodHandler(baseHandler)")
	g.P()
	g.P("return basePath, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {")
	g.P("// 记录请求信息")
	g.P("log.Printf(\"HTTP %s request to %s\", r.Method, r.URL.Path)")
	g.P()
	g.P("// 根据配置和HTTP方法分发请求")
	g.P("switch r.Method {")
	g.P("case ", connectx.HTTPMethodGET, ":")
	g.P("if config.EnableGET {")
	g.P("if err := methodHandler.HandleGET(w, r, r.URL.Path); err != nil {")
	g.P("log.Printf(\"GET request error: %v\", err)")
	g.P("}")
	g.P("} else {")
	g.P("http.Error(w, \"GET method not allowed\", http.StatusMethodNotAllowed)")
	g.P("}")
	g.P("case ", connectx.HTTPMethodPOST, ":")
	g.P("if config.EnablePOST {")
	g.P("if err := methodHandler.HandlePOST(w, r, r.URL.Path); err != nil {")
	g.P("log.Printf(\"POST request error: %v\", err)")
	g.P("}")
	g.P("} else {")
	g.P("http.Error(w, \"POST method not allowed\", http.StatusMethodNotAllowed)")
	g.P("}")
	g.P("case ", connectx.HTTPMethodDELETE, ":")
	g.P("if config.EnableDELETE {")
	g.P("if err := methodHandler.HandleDELETE(w, r, r.URL.Path); err != nil {")
	g.P("log.Printf(\"DELETE request error: %v\", err)")
	g.P("}")
	g.P("} else {")
	g.P("http.Error(w, \"DELETE method not allowed\", http.StatusMethodNotAllowed)")
	g.P("}")
	g.P("case ", connectx.HTTPMethodPUT, ":")
	g.P("if config.EnablePUT {")
	g.P("if err := methodHandler.HandlePUT(w, r, r.URL.Path); err != nil {")
	g.P("log.Printf(\"PUT request error: %v\", err)")
	g.P("}")
	g.P("} else {")
	g.P("http.Error(w, \"PUT method not allowed\", http.StatusMethodNotAllowed)")
	g.P("}")
	g.P("case ", connectx.HTTPMethodOPTIONS, ":")
	g.P("if config.EnableCORS {")
	g.P("// 处理CORS预检请求")
	g.P("w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")")
	g.P("w.Header().Set(\"Access-Control-Allow-Methods\", ", connectx.HTTPMethodGET, "+\", \"+", connectx.HTTPMethodPOST, "+\", \"+", connectx.HTTPMethodPUT, "+\", \"+", connectx.HTTPMethodDELETE, "+\", \"+", connectx.HTTPMethodOPTIONS, ")")
	g.P("w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization, x-token\")")
	g.P("w.WriteHeader(http.StatusOK)")
	g.P("} else {")
	g.P("http.Error(w, \"OPTIONS method not allowed\", http.StatusMethodNotAllowed)")
	g.P("}")
	g.P("default:")
	g.P("http.Error(w, \"Method not allowed\", http.StatusMethodNotAllowed)")
	g.P("}")
	g.P("})")
	g.P("}")
	g.P()
}

// generateUnifiedMethodHandler 生成统一方法处理器
func generateUnifiedMethodHandler(g *protogen.GeneratedFile, service *protogen.Service) {
	serviceName := service.GoName
	handlerName := "Unified" + serviceName + "MethodHandler"

	g.P("// ", handlerName, " 统一的方法处理器，HTTP和gRPC走同一套逻辑")
	g.P("type ", handlerName, " struct {")
	g.P("server       ", serviceName, "Server")
	g.P("interceptors []Interceptor")
	g.P("}")
	g.P()

	g.P("// NewUnified", serviceName, "MethodHandler 创建统一方法处理器")
	g.P("func NewUnified", serviceName, "MethodHandler(server ", serviceName, "Server, interceptors []Interceptor) *", handlerName, " {")
	g.P("return &", handlerName, "{")
	g.P("server:       server,")
	g.P("interceptors: interceptors,")
	g.P("}")
	g.P("}")
	g.P()

	g.P("// HandleRequest 处理HTTP请求，直接调用gRPC方法")
	g.P("func (h *", handlerName, ") HandleRequest(w http.ResponseWriter, r *http.Request, methodName string) {")
	g.P("ctx := r.Context()")
	g.P()
	g.P("// 从context中提取trace_id")
	g.P("traceID := \"\"")
	g.P("if tid := ctx.Value(\"trace_id\"); tid != nil {")
	g.P("if tidStr, ok := tid.(string); ok {")
	g.P("traceID = tidStr")
	g.P("}")
	g.P("}")
	g.P("// 如果没有从context获取到，尝试从logv获取")
	g.P("if traceID == \"\" {")
	g.P("traceID = logv.GetTraceID(ctx)")
	g.P("}")
	g.P("// 如果还是没有，尝试从HTTP头获取")
	g.P("if traceID == \"\" {")
	g.P("traceID = r.Header.Get(\"X-Trace-ID\")")
	g.P("}")
	g.P()
	g.P("// 提取HTTP headers并添加到context")
	g.P("headers := make(map[string][]string)")
	g.P("for key, values := range r.Header {")
	g.P("headers[strings.ToLower(key)] = values")
	g.P("}")
	g.P("ctx = context.WithValue(ctx, \"headers\", headers)")
	g.P("// 确保trace_id在context中")
	g.P("if traceID != \"\" {")
	g.P("ctx = context.WithValue(ctx, \"trace_id\", traceID)")
	g.P("}")
	g.P()
	g.P("// 运行拦截器")
	g.P("for _, interceptor := range h.interceptors {")
	g.P("var err error")
	g.P("ctx, err = interceptor.Intercept(ctx, methodName, nil)")
	g.P("if err != nil {")
	g.P("// 处理Connect错误")
	g.P("if connectErr, ok := err.(*", connectx.ConnectPackage.Ident("Error"), "); ok {")
	g.P("switch connectErr.Code() {")
	g.P("case ", connectx.ConnectPackage.Ident("CodeUnauthenticated"), ":")
	g.P("h.writeErrorResponse(w, \"UNAUTHORIZED\", \"认证失败\", connectErr.Message(), http.StatusUnauthorized, traceID)")
	g.P("case ", connectx.ConnectPackage.Ident("CodePermissionDenied"), ":")
	g.P("h.writeErrorResponse(w, \"FORBIDDEN\", \"权限不足\", connectErr.Message(), http.StatusForbidden, traceID)")
	g.P("default:")
	g.P("h.writeErrorResponse(w, \"INTERNAL_ERROR\", \"内部错误\", connectErr.Message(), http.StatusInternalServerError, traceID)")
	g.P("}")
	g.P("} else {")
	g.P("h.writeErrorResponse(w, \"INTERNAL_ERROR\", \"内部服务器错误\", err.Error(), http.StatusInternalServerError, traceID)")
	g.P("}")
	g.P("return")
	g.P("}")
	g.P("}")
	g.P()
	g.P("// 解析请求参数")
	g.P("var requestData map[string]interface{}")
	g.P()
	g.P("if r.Method == ", connectx.HTTPMethodGET, " {")
	g.P("// GET请求从查询参数中获取数据")
	g.P("requestData = make(map[string]interface{})")
	g.P("for key, values := range r.URL.Query() {")
	g.P("if len(values) == 1 {")
	g.P("requestData[key] = values[0]")
	g.P("} else {")
	g.P("requestData[key] = values")
	g.P("}")
	g.P("}")
	g.P("} else {")
	g.P("// POST/PUT/DELETE请求从请求体中获取JSON数据")
	g.P("// 先检查请求体是否为空")
	g.P("if r.ContentLength == 0 || r.Body == nil {")
	g.P("// 空请求体，初始化为空map")
	g.P("requestData = make(map[string]interface{})")
	g.P("} else {")
	g.P("// 尝试解析JSON")
	g.P("decoder := json.NewDecoder(r.Body)")
	g.P("if err := decoder.Decode(&requestData); err != nil {")
	g.P("// 如果是EOF错误（空body），初始化为空map")
	g.P("if err == ", g.QualifiedGoIdent(connectx.IoPackage.Ident("EOF")), " {")
	g.P("requestData = make(map[string]interface{})")
	g.P("} else {")
	g.P("h.writeErrorResponse(w, \"INVALID_JSON\", \"JSON格式错误\", err.Error(), http.StatusBadRequest, traceID)")
	g.P("return")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P()
	g.P("// 根据方法名调用对应的gRPC方法")
	g.P("switch methodName {")

	for _, method := range service.Methods {
		g.P("case \"", method.GoName, "\":")
		g.P("h.handle", method.GoName, "(ctx, w, requestData)")
	}

	g.P("default:")
	g.P("http.Error(w, \"Method not found\", http.StatusNotFound)")
	g.P("}")
	g.P("}")
	g.P()

	// 为每个方法生成处理函数
	for _, method := range service.Methods {
		requestType := method.Input.GoIdent.GoName
		//responseType := method.Output.GoIdent.GoName

		g.P("// handle", method.GoName, " 处理", method.GoName, "方法")
		g.P("func (h *", handlerName, ") handle", method.GoName, "(ctx context.Context, w http.ResponseWriter, requestData map[string]interface{}) {")
		g.P("// 从context中提取trace_id")
		g.P("traceID := \"\"")
		g.P("if tid := ctx.Value(\"trace_id\"); tid != nil {")
		g.P("if tidStr, ok := tid.(string); ok {")
		g.P("traceID = tidStr")
		g.P("}")
		g.P("}")
		g.P("// 如果没有从context获取到，尝试从logv获取")
		g.P("if traceID == \"\" {")
		g.P("traceID = logv.GetTraceID(ctx)")
		g.P("}")
		g.P()
		g.P()
		g.P("// 构造gRPC请求")
		g.P("req := &", requestType, "{}")
		g.P()

		g.P("// 动态映射请求数据到protobuf结构体")
		g.P("if err := h.mapRequestDataToProto(requestData, req); err != nil {")
		g.P("log.Error().Str(\"trace_id\", traceID).Err(err).Msg(\"请求数据映射失败\")")
		g.P("h.writeErrorResponse(w, \"INVALID_REQUEST_DATA\", \"请求数据格式错误\", err.Error(), http.StatusBadRequest, traceID)")
		g.P("return")
		g.P("}")
		g.P()

		g.P("// 直接调用标准gRPC方法")
		g.P("resp, err := h.server.", method.GoName, "(ctx, req)")
		g.P("if err != nil {")
		g.P("log.Error().Str(\"trace_id\", traceID).Err(err).Msg(\"gRPC方法执行失败\")")
		g.P("h.writeErrorResponse(w, \"GRPC_ERROR\", \"gRPC方法执行失败\", err.Error(), http.StatusInternalServerError, traceID)")
		g.P("return")
		g.P("}")
		g.P()
		g.P("// 记录响应结果")
		g.P("log.Debug().Str(\"trace_id\", traceID).Interface(\"response\", resp).Msg(\"gRPC响应结果\")")
		g.P()
		g.P("// 返回JSON响应（使用 protojson 以保留零值字段）")
		g.P("w.Header().Set(\"Content-Type\", \"application/json\")")
		g.P("w.Header().Set(\"X-Trace-ID\", traceID) // 将trace_id添加到响应头")
		g.P()
		g.P("// 使用 protojson.MarshalOptions 配置以包含零值字段")
		g.P("marshaler := protojson.MarshalOptions{")
		g.P("EmitUnpopulated: true, // 包含零值字段")
		g.P("UseProtoNames:   false, // 使用 JSON 名称而非 proto 名称")
		g.P("}")
		g.P("jsonBytes, err := marshaler.Marshal(resp)")
		g.P("if err != nil {")
		g.P("log.Error().Str(\"trace_id\", traceID).Err(err).Msg(\"响应编码失败\")")
		g.P("h.writeErrorResponse(w, \"RESPONSE_ENCODE_ERROR\", \"响应编码失败\", err.Error(), http.StatusInternalServerError, traceID)")
		g.P("return")
		g.P("}")
		g.P()
		g.P("if _, err := w.Write(jsonBytes); err != nil {")
		g.P("log.Error().Str(\"trace_id\", traceID).Err(err).Msg(\"写入响应失败\")")
		g.P("}")
		g.P("}")
		g.P()
	}

	// 添加错误响应方法
	g.P("// writeErrorResponse 写入自定义JSON错误响应")
	g.P("func (h *", handlerName, ") writeErrorResponse(w http.ResponseWriter, code string, message string, detail string, httpStatus int, traceID string) {")
	g.P("w.Header().Set(\"Content-Type\", \"application/json\")")
	g.P("w.Header().Set(\"X-Trace-ID\", traceID)")
	g.P("w.WriteHeader(httpStatus)")
	g.P()
	g.P("// 尝试从错误详情中解析ret或code状态码")
	g.P("retCode := -2000 // 默认错误码")
	g.P()
	g.P("// 尝试解析JSON格式的错误信息")
	g.P("var errorData map[string]interface{}")
	g.P("if err := json.Unmarshal([]byte(detail), &errorData); err == nil {")
	g.P("// 优先查找ret字段")
	g.P("if ret, ok := errorData[\"ret\"]; ok {")
	g.P("if retInt, ok := ret.(float64); ok {")
	g.P("retCode = int(retInt)")
	g.P("} else if retStr, ok := ret.(string); ok {")
	g.P("if parsedRet, err := fmt.Sscanf(retStr, \"%d\"); err == nil && parsedRet == 1 {")
	g.P("var tempRet int")
	g.P("fmt.Sscanf(retStr, \"%d\", &tempRet)")
	g.P("retCode = tempRet")
	g.P("}")
	g.P("}")
	g.P("} else if code, ok := errorData[\"code\"]; ok {")
	g.P("// 如果没有ret字段，查找code字段")
	g.P("if codeInt, ok := code.(float64); ok {")
	g.P("retCode = int(codeInt)")
	g.P("} else if codeStr, ok := code.(string); ok {")
	g.P("if parsedCode, err := fmt.Sscanf(codeStr, \"%d\"); err == nil && parsedCode == 1 {")
	g.P("var tempCode int")
	g.P("fmt.Sscanf(codeStr, \"%d\", &tempCode)")
	g.P("retCode = tempCode")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P()
	g.P("// 如果没有从错误中解析到状态码，使用默认的错误类型映射")
	g.P("if retCode == -2000 {")
	g.P("switch code {")
	g.P("case \"UNAUTHORIZED\":")
	g.P("retCode = -2001")
	g.P("case \"FORBIDDEN\":")
	g.P("retCode = -2002")
	g.P("case \"INVALID_JSON\":")
	g.P("retCode = -2003")
	g.P("case \"INVALID_REQUEST_DATA\":")
	g.P("retCode = -2004")
	g.P("case \"GRPC_ERROR\":")
	g.P("retCode = -2005")
	g.P("case \"RESPONSE_ENCODE_ERROR\":")
	g.P("retCode = -2006")
	g.P("}")
	g.P("}")
	g.P()
	g.P("errorResponse := map[string]interface{}{")
	g.P("\"ret\": retCode,")
	g.P("\"data\": \"\",")
	g.P("\"msg\": message + \": \" + detail,")
	g.P("\"trace_id\": traceID,")
	g.P("\"timestamp\": time.Now().Format(time.RFC3339),")
	g.P("}")
	g.P()
	g.P("if err := json.NewEncoder(w).Encode(errorResponse); err != nil {")
	g.P("log.Error().Str(\"trace_id\", traceID).Err(err).Msg(\"错误响应编码失败\")")
	g.P("}")
	g.P("}")
	g.P()

	// 添加通用的数据映射方法
	g.P("// mapRequestDataToProto 将请求数据映射到protobuf结构体")
	g.P("func (h *", handlerName, ") mapRequestDataToProto(requestData map[string]interface{}, target interface{}) error {")
	g.P("if requestData == nil || target == nil {")
	g.P("return nil")
	g.P("}")
	g.P()
	g.P("// 使用反射获取目标结构体的信息")
	g.P("targetValue := reflect.ValueOf(target)")
	g.P("if targetValue.Kind() != reflect.Ptr || targetValue.Elem().Kind() != reflect.Struct {")
	g.P("return errors.New(\"target must be a pointer to struct\")")
	g.P("}")
	g.P()
	g.P("targetStruct := targetValue.Elem()")
	g.P("targetType := targetStruct.Type()")
	g.P()
	g.P("// 遍历结构体的所有字段")
	g.P("for i := 0; i < targetStruct.NumField(); i++ {")
	g.P("field := targetStruct.Field(i)")
	g.P("fieldType := targetType.Field(i)")
	g.P()
	g.P("// 跳过不可设置的字段")
	g.P("if !field.CanSet() {")
	g.P("continue")
	g.P("}")
	g.P()
	g.P("// 获取字段名（支持json tag）")
	g.P("fieldName := fieldType.Name")
	g.P("if jsonTag := fieldType.Tag.Get(\"json\"); jsonTag != \"\" {")
	g.P("if commaIdx := strings.Index(jsonTag, \",\"); commaIdx > 0 {")
	g.P("fieldName = jsonTag[:commaIdx]")
	g.P("} else {")
	g.P("fieldName = jsonTag")
	g.P("}")
	g.P("}")
	g.P()
	g.P("// 将字段名转换为小写进行匹配（支持驼峰和下划线）")
	g.P("possibleKeys := []string{")
	g.P("fieldName,")
	g.P("strings.ToLower(fieldName),")
	g.P("strings.ToLower(fieldType.Name),")
	g.P("}")
	g.P()
	g.P("// 尝试从请求数据中找到对应的值")
	g.P("var value interface{}")
	g.P("var found bool")
	g.P("for _, key := range possibleKeys {")
	g.P("if v, ok := requestData[key]; ok {")
	g.P("value = v")
	g.P("found = true")
	g.P("break")
	g.P("}")
	g.P("}")
	g.P()
	g.P("if !found {")
	g.P("continue")
	g.P("}")
	g.P()
	g.P("// 根据字段类型设置值")
	g.P("if err := h.setFieldValue(field, value); err != nil {")
	g.P("return fmt.Errorf(\"failed to set field %s: %w\", fieldType.Name, err)")
	g.P("}")
	g.P("}")
	g.P()
	g.P("return nil")
	g.P("}")
	g.P()

	g.P("// setFieldValue 设置字段值")
	g.P("func (h *", handlerName, ") setFieldValue(field reflect.Value, value interface{}) error {")
	g.P("if value == nil {")
	g.P("return nil")
	g.P("}")
	g.P()
	g.P("fieldType := field.Type()")
	g.P("valueType := reflect.TypeOf(value)")
	g.P()
	g.P("// 如果类型完全匹配，直接设置")
	g.P("if valueType == fieldType {")
	g.P("field.Set(reflect.ValueOf(value))")
	g.P("return nil")
	g.P("}")
	g.P()
	g.P("// 类型转换")
	g.P("switch fieldType.Kind() {")
	g.P("case reflect.String:")
	g.P("if str, ok := value.(string); ok {")
	g.P("field.SetString(str)")
	g.P("} else {")
	g.P("field.SetString(fmt.Sprintf(\"%v\", value))")
	g.P("}")
	g.P()
	g.P("case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:")
	g.P("switch v := value.(type) {")
	g.P("case int:")
	g.P("field.SetInt(int64(v))")
	g.P("case int32:")
	g.P("field.SetInt(int64(v))")
	g.P("case int64:")
	g.P("field.SetInt(v)")
	g.P("case float64:")
	g.P("field.SetInt(int64(v))")
	g.P("case string:")
	g.P("if intVal, err := fmt.Sscanf(v, \"%d\"); err == nil && intVal == 1 {")
	g.P("var i int64")
	g.P("fmt.Sscanf(v, \"%d\", &i)")
	g.P("field.SetInt(i)")
	g.P("} else {")
	g.P("return fmt.Errorf(\"cannot convert string %s to int\", v)")
	g.P("}")
	g.P("default:")
	g.P("return fmt.Errorf(\"cannot convert %T to int\", value)")
	g.P("}")
	g.P()
	g.P("case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:")
	g.P("switch v := value.(type) {")
	g.P("case uint:")
	g.P("field.SetUint(uint64(v))")
	g.P("case uint32:")
	g.P("field.SetUint(uint64(v))")
	g.P("case uint64:")
	g.P("field.SetUint(v)")
	g.P("case int:")
	g.P("if v >= 0 {")
	g.P("field.SetUint(uint64(v))")
	g.P("} else {")
	g.P("return fmt.Errorf(\"cannot convert negative int to uint\")")
	g.P("}")
	g.P("case float64:")
	g.P("if v >= 0 {")
	g.P("field.SetUint(uint64(v))")
	g.P("} else {")
	g.P("return fmt.Errorf(\"cannot convert negative float to uint\")")
	g.P("}")
	g.P("default:")
	g.P("return fmt.Errorf(\"cannot convert %T to uint\", value)")
	g.P("}")
	g.P()
	g.P("case reflect.Float32, reflect.Float64:")
	g.P("switch v := value.(type) {")
	g.P("case float32:")
	g.P("field.SetFloat(float64(v))")
	g.P("case float64:")
	g.P("field.SetFloat(v)")
	g.P("case int:")
	g.P("field.SetFloat(float64(v))")
	g.P("case int64:")
	g.P("field.SetFloat(float64(v))")
	g.P("default:")
	g.P("return fmt.Errorf(\"cannot convert %T to float\", value)")
	g.P("}")
	g.P()
	g.P("case reflect.Bool:")
	g.P("switch v := value.(type) {")
	g.P("case bool:")
	g.P("field.SetBool(v)")
	g.P("case string:")
	g.P("if b, err := fmt.Sscanf(v, \"%t\"); err == nil && b == 1 {")
	g.P("var boolVal bool")
	g.P("fmt.Sscanf(v, \"%t\", &boolVal)")
	g.P("field.SetBool(boolVal)")
	g.P("} else {")
	g.P("return fmt.Errorf(\"cannot convert string %s to bool\", v)")
	g.P("}")
	g.P("default:")
	g.P("return fmt.Errorf(\"cannot convert %T to bool\", value)")
	g.P("}")
	g.P()
	g.P("case reflect.Slice:")
	g.P("// 处理切片类型")
	g.P("if arr, ok := value.([]interface{}); ok {")
	g.P("newSlice := reflect.MakeSlice(fieldType, len(arr), len(arr))")
	g.P("for i, item := range arr {")
	g.P("if err := h.setFieldValue(newSlice.Index(i), item); err != nil {")
	g.P("return fmt.Errorf(\"failed to set slice element %d: %w\", i, err)")
	g.P("}")
	g.P("}")
	g.P("field.Set(newSlice)")
	g.P("} else {")
	g.P("return fmt.Errorf(\"cannot convert %T to slice\", value)")
	g.P("}")
	g.P()
	g.P("default:")
	g.P("// 对于其他复杂类型，尝试JSON序列化/反序列化")
	g.P("jsonBytes, err := json.Marshal(value)")
	g.P("if err != nil {")
	g.P("return fmt.Errorf(\"failed to marshal value: %w\", err)")
	g.P("}")
	g.P()
	g.P("newValue := reflect.New(fieldType)")
	g.P("if err := json.Unmarshal(jsonBytes, newValue.Interface()); err != nil {")
	g.P("return fmt.Errorf(\"failed to unmarshal to field type: %w\", err)")
	g.P("}")
	g.P()
	g.P("field.Set(newValue.Elem())")
	g.P("}")
	g.P()
	g.P("return nil")
	g.P("}")
}

func generatedConstants(g *protogen.GeneratedFile, file *protogen.File, generatedGlobals map[string]bool) {

	//1. 常量定义
	g.P("const _ = ", connectx.ConnectPackage.Ident("IsAtLeastVersion1_13_0"))
	g.P()

	// 为每个服务生成常量和类型定义
	for _, service := range file.Services {
		generateServiceConstants(g, service, file)
		generateServiceTypes(g, service, file)
	}
}

// generateServiceConstants 生成服务相关的常量
func generateServiceConstants(g *protogen.GeneratedFile, service *protogen.Service, file *protogen.File) {
	serviceName := service.GoName
	// 使用 proto 文件的实际包名，而不是 Go 包名
	packageName := string(file.Proto.GetPackage())
	if packageName == "" {
		// 如果没有包名，使用 Go 包名作为后备
		packageName = string(file.GoPackageName)
	}

	// 生成服务名称常量
	g.P("const (")
	g.P("// ", serviceName, "Name is the fully-qualified name of the ", serviceName, " service.")
	g.P(serviceName, "Name = \"/", packageName, ".", serviceName, "/\"")
	g.P(")")
	g.P()

	// 生成RPC过程名称常量
	g.P("// These constants are the fully-qualified names of the RPCs defined in this package. They're")
	g.P("// exposed at runtime as Spec.Procedure and as the final two segments of the HTTP route.")
	g.P("//")
	g.P("// Note that these are different from the fully-qualified method names used by")
	g.P("// google.golang.org/protobuf/reflect/protoreflect. To convert from these constants to")
	g.P("// reflection-formatted method names, remove the leading slash and convert the remaining slash to a")
	g.P("// period.")
	g.P("const (")

	for _, method := range service.Methods {
		procedureName := serviceName + method.GoName + "Procedure"
		g.P("// ", procedureName, " is the fully-qualified name of the ", serviceName, "'s ", method.GoName, " RPC.")
		g.P(procedureName, " = \"/", packageName, ".", serviceName, "/", method.GoName, "\"")
	}
	g.P(")")
	g.P()

}

// generateServiceTypes 生成服务相关的类型定义
func generateServiceTypes(g *protogen.GeneratedFile, service *protogen.Service, file *protogen.File) {
	serviceName := service.GoName
	// 使用 proto 文件的实际包名，而不是 Go 包名
	packageName := string(file.Proto.GetPackage())
	if packageName == "" {
		// 如果没有包名，使用 Go 包名作为后备
		packageName = string(file.GoPackageName)
	}
	clientInterfaceName := serviceName + "Client"
	clientStructName := strings.ToLower(serviceName[:1]) + serviceName[1:] + "Client"
	handlerInterfaceName := serviceName + "Handler"
	unimplementedHandlerName := "Unimplemented" + serviceName + "Handler"

	// 生成客户端接口
	g.P("// ", clientInterfaceName, " is a client for the ", packageName, ".", serviceName, " service.")
	g.P("type ", clientInterfaceName, " interface {")
	for _, method := range service.Methods {
		requestType := method.Input.GoIdent.GoName
		responseType := method.Output.GoIdent.GoName
		g.P(method.GoName, "(context.Context, *", connectx.ConnectPackage.Ident("Request"), "[", requestType, "]) (*", connectx.ConnectPackage.Ident("Response"), "[", responseType, "], error)")
	}
	g.P("}")
	g.P()

	// 生成客户端构造函数
	g.P("// New", serviceName, "Client constructs a client for the ", packageName, ".", serviceName, " service. By default, it")
	g.P("// uses the Connect protocol with the binary Protobuf Codec, asks for gzipped responses, and sends")
	g.P("// uncompressed requests. To use the gRPC or gRPC-Web protocols, supply the connect.WithGRPC() or")
	g.P("// connect.WithGRPCWeb() options.")
	g.P("//")
	g.P("// The URL supplied here should be the base URL for the Connect or gRPC server (for example,")
	g.P("// http://api.acme.com or https://acme.com/grpc).")
	g.P("func New", serviceName, "Client(httpClient ", connectx.ConnectPackage.Ident("HTTPClient"), ", baseURL string, opts ...", connectx.ConnectPackage.Ident("ClientOption"), ") ", clientInterfaceName, " {")
	g.P("baseURL = strings.TrimRight(baseURL, \"/\")")
	g.P("return &", clientStructName, "{")

	for _, method := range service.Methods {
		methodNameLower := strings.ToLower(method.GoName[:1]) + method.GoName[1:]
		procedureName := serviceName + method.GoName + "Procedure"
		requestType := method.Input.GoIdent.GoName
		responseType := method.Output.GoIdent.GoName

		g.P(methodNameLower, ": ", connectx.ConnectPackage.Ident("NewClient"), "[", requestType, ", ", responseType, "](")
		g.P("httpClient,")
		g.P("baseURL+", procedureName, ",")
		g.P(connectx.ConnectPackage.Ident("WithSchema"), "(Get", serviceName, method.GoName, "MethodDescriptor()),")
		g.P(connectx.ConnectPackage.Ident("WithClientOptions"), "(opts...),")
		g.P("),")
	}
	g.P("}")
	g.P("}")
	g.P()

	// 生成客户端实现结构体
	g.P("// ", clientStructName, " implements ", clientInterfaceName, ".")
	g.P("type ", clientStructName, " struct {")
	for _, method := range service.Methods {
		methodNameLower := strings.ToLower(method.GoName[:1]) + method.GoName[1:]
		requestType := method.Input.GoIdent.GoName
		responseType := method.Output.GoIdent.GoName
		g.P(methodNameLower, " *", connectx.ConnectPackage.Ident("Client"), "[", requestType, ", ", responseType, "]")
	}
	g.P("}")
	g.P()

	// 生成客户端方法实现
	for _, method := range service.Methods {
		methodNameLower := strings.ToLower(method.GoName[:1]) + method.GoName[1:]
		requestType := method.Input.GoIdent.GoName
		responseType := method.Output.GoIdent.GoName

		g.P("// ", method.GoName, " calls ", packageName, ".", serviceName, ".", method.GoName, ".")
		g.P("func (c *", clientStructName, ") ", method.GoName, "(ctx context.Context, req *", connectx.ConnectPackage.Ident("Request"), "[", requestType, "]) (*", connectx.ConnectPackage.Ident("Response"), "[", responseType, "], error) {")
		g.P("return c.", methodNameLower, ".CallUnary(ctx, req)")
		g.P("}")
		g.P()
	}

	// 生成服务端处理器接口
	g.P("// ", handlerInterfaceName, " is an implementation of the ", packageName, ".", serviceName, " service.")
	g.P("type ", handlerInterfaceName, " interface {")
	for _, method := range service.Methods {
		requestType := method.Input.GoIdent.GoName
		responseType := method.Output.GoIdent.GoName
		g.P(method.GoName, "(context.Context, *", connectx.ConnectPackage.Ident("Request"), "[", requestType, "]) (*", connectx.ConnectPackage.Ident("Response"), "[", responseType, "], error)")
	}
	g.P("}")
	g.P()

	// 生成服务端处理器构造函数
	g.P("// New", serviceName, "Handler builds an HTTP handler from the service implementation. It returns the")
	g.P("// path on which to mount the handler and the handler itself.")
	g.P("//")
	g.P("// By default, handlers support the Connect, gRPC, and gRPC-Web protocols with the binary Protobuf")
	g.P("// and JSON codecs. They also support gzip compression.")
	g.P("func New", serviceName, "Handler(svc ", handlerInterfaceName, ", opts ...", connectx.ConnectPackage.Ident("HandlerOption"), ") (string, http.Handler) {")

	// 为每个方法创建处理器
	for _, method := range service.Methods {
		serviceNameLower := strings.ToLower(serviceName)
		procedureName := serviceName + method.GoName + "Procedure"

		g.P(serviceNameLower, method.GoName, "Handler := ", connectx.ConnectPackage.Ident("NewUnaryHandler"), "(")
		g.P(procedureName, ",")
		g.P("svc.", method.GoName, ",")
		g.P(connectx.ConnectPackage.Ident("WithSchema"), "(Get", serviceName, method.GoName, "MethodDescriptor()),")
		g.P(connectx.ConnectPackage.Ident("WithHandlerOptions"), "(opts...),")
		g.P(")")
	}

	g.P("return ", serviceName, "Name, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {")
	g.P("switch r.URL.Path {")

	for _, method := range service.Methods {
		serviceNameLower := strings.ToLower(serviceName)
		procedureName := serviceName + method.GoName + "Procedure"
		g.P("case ", procedureName, ":")
		g.P(serviceNameLower, method.GoName, "Handler.ServeHTTP(w, r)")
	}

	g.P("default:")
	g.P("http.NotFound(w, r)")
	g.P("}")
	g.P("})")
	g.P("}")
	g.P()

	// 生成未实现的处理器
	g.P("// ", unimplementedHandlerName, " returns CodeUnimplemented from all methods.")
	g.P("type ", unimplementedHandlerName, " struct{}")
	g.P()

	for _, method := range service.Methods {
		requestType := method.Input.GoIdent.GoName
		responseType := method.Output.GoIdent.GoName

		g.P("func (", unimplementedHandlerName, ") ", method.GoName, "(context.Context, *", connectx.ConnectPackage.Ident("Request"), "[", requestType, "]) (*", connectx.ConnectPackage.Ident("Response"), "[", responseType, "], error) {")
		g.P("return nil, ", connectx.ConnectPackage.Ident("NewError"), "(", connectx.ConnectPackage.Ident("CodeUnimplemented"), ", errors.New(\"", packageName, ".", serviceName, ".", method.GoName, " is not implemented\"))")
		g.P("}")
		g.P()
	}

}

// ---------------------------------------------------------公共部分-------------------------------------------------------------------
// GenerateCommFile 生成包级别的通用文件
func GenerateCommFile(plugin *protogen.Plugin, file *protogen.File) {
	// 生成 .connectx.comm.go 文件，使用 go_package 路径
	goPackagePath := string(file.GoImportPath)
	// 从 go_package 路径中提取最后一部分作为目录名
	var packageDir string
	if lastSlash := strings.LastIndex(goPackagePath, "/"); lastSlash >= 0 {
		packageDir = goPackagePath[lastSlash+1:]
	} else {
		packageDir = goPackagePath
	}
	commFile := plugin.NewGeneratedFile(
		packageDir+"/connectx.comm.go",
		file.GoImportPath,
	)

	// 确保目标目录存在
	if err := os.MkdirAll(path.Dir(file.GeneratedFilenamePrefix), 0755); err != nil {
		plugin.Error(err)
		return
	}

	// 生成包声明和导入
	commFile.P("package ", file.GoPackageName)
	commFile.P()
	commFile.P("import (")
	commFile.P(`"bytes"`)
	commFile.P(`"context"`)
	commFile.P(`"encoding/json"`)
	commFile.P(`"fmt"`)
	commFile.P(`"time"`)
	commFile.P(`"crypto/rand"`)
	commFile.P(`"encoding/hex"`)
	commFile.P(`"strings"`)
	commFile.P(`"net/http"`)
	commFile.P(`"gitee.com/filters/utils/logv"`)
	commFile.P(`"github.com/rs/zerolog"`)
	commFile.P(`"github.com/rs/zerolog/log"`)
	commFile.P(`"sync"`)
	commFile.P(")")
	commFile.P()

	commFile.P("const (")
	commFile.P(`POST = "POST"`)
	commFile.P(`GET = "GET"`)
	commFile.P(`DELETE = "DELETE"`)
	commFile.P(`PUT = "PUT"`)
	commFile.P(`OPTIONS = "OPTIONS"`)
	commFile.P(`HEAD = "HEAD"`)
	commFile.P(`PATCH = "PATCH"`)
	commFile.P(")")

	// 生成通用接口和结构体
	generateCommInterfaces(commFile)
	generateCommStructs(commFile)
	generateCommFunctions(commFile)

	// 生成 trace ID 相关代码
	generateTraceIDCode(commFile)

	// 生成 ServiceChain 相关代码
	generateServiceChain(commFile, file)

	generateService(commFile, file)

}

// generateCommInterfaces 生成通用接口
func generateCommInterfaces(g *protogen.GeneratedFile) {
	// Interceptor 接口
	g.P("// ", connectx.GlobalNames.InterceptorName, " 定义拦截器接口")
	g.P("type ", connectx.GlobalNames.InterceptorName, " interface {")
	g.P("Intercept(ctx context.Context, method string, req interface{}) (context.Context, error)")
	g.P("}")
	g.P()

	// HTTPMethodHandler 接口
	g.P("// ", connectx.GlobalNames.HTTPMethodHandler, " 定义HTTP方法处理器接口")
	g.P("type ", connectx.GlobalNames.HTTPMethodHandler, " interface {")
	g.P("HandleGET(w http.ResponseWriter, r *http.Request, path string) error")
	g.P("HandlePOST(w http.ResponseWriter, r *http.Request, path string) error")
	g.P("HandleDELETE(w http.ResponseWriter, r *http.Request, path string) error")
	g.P("HandlePUT(w http.ResponseWriter, r *http.Request, path string) error")
	g.P("}")
	g.P()
}

// generateCommStructs 生成通用结构体
func generateCommStructs(g *protogen.GeneratedFile) {
	// DefaultHTTPMethodHandler 结构体
	g.P("// ", connectx.GlobalNames.DefaultHTTPMethodHandler, " 默认HTTP方法处理器实现")
	g.P("type ", connectx.GlobalNames.DefaultHTTPMethodHandler, " struct {")
	g.P("connectHandler http.Handler")
	g.P("}")
	g.P()

	// HTTPMethodConfig 结构体
	g.P("// HTTPMethodConfig HTTP方法配置")
	g.P("type HTTPMethodConfig struct {")
	g.P("EnableGET    bool")
	g.P("EnablePOST   bool")
	g.P("EnablePUT    bool")
	g.P("EnableDELETE bool")
	g.P("EnableCORS   bool")
	g.P("}")
	g.P()

	// MethodHTTPConfig 结构体
	g.P("// MethodHTTPConfig 定义每个方法支持的HTTP方法")
	g.P("type MethodHTTPConfig struct {")
	g.P("MethodName     string   // gRPC方法名，如 \"Greet\", \"Hello\"")
	g.P("AllowedMethods []string // 允许的HTTP方法，如 [\"GET\", \"POST\", \"DELETE\"]")
	g.P("}")
	g.P()
}

// generateCommFunctions 生成通用函数
func generateCommFunctions(g *protogen.GeneratedFile) {
	// NewDefaultHTTPMethodHandler 构造函数
	g.P("// NewDefaultHTTPMethodHandler 创建默认HTTP方法处理器")
	g.P("func NewDefaultHTTPMethodHandler(connectHandler http.Handler) *", connectx.GlobalNames.DefaultHTTPMethodHandler, " {")
	g.P("return &", connectx.GlobalNames.DefaultHTTPMethodHandler, "{connectHandler: connectHandler}")
	g.P("}")
	g.P()

	// DefaultHTTPMethodConfig 函数
	g.P("// DefaultHTTPMethodConfig 默认HTTP方法配置")
	g.P("func DefaultHTTPMethodConfig() *HTTPMethodConfig {")
	g.P("return &HTTPMethodConfig{")
	g.P("EnableGET:    true,")
	g.P("EnablePOST:   true,")
	g.P("EnablePUT:    true,")
	g.P("EnableDELETE: true,")
	g.P("EnableCORS:   true,")
	g.P("}")
	g.P("}")
	g.P()

	// getKeys 工具函数
	g.P("// GetKeys 获取map的所有key")
	g.P("func GetKeys(m map[string]bool) []string {")
	g.P("keys := make([]string, 0, len(m))")
	g.P("for k := range m {")
	g.P("keys = append(keys, k)")
	g.P("}")
	g.P("return keys")
	g.P("}")
	g.P()

	// generateTraceID 生成trace_id
	g.P("// generateTraceID 生成唯一的trace_id")
	g.P("func generateTraceID() string {")
	g.P("bytes := make([]byte, 16)")
	g.P("if _, err := rand.Read(bytes); err != nil {")
	g.P("// 如果随机数生成失败，使用时间戳作为后备")
	g.P("return fmt.Sprintf(\"trace_%d\", time.Now().UnixNano())")
	g.P("}")
	g.P("return hex.EncodeToString(bytes)")
	g.P("}")
	g.P()

	// GetTraceIDFromContext 从context中提取trace_id
	g.P("// GetTraceIDFromContext 从context中提取trace_id")
	g.P("func GetTraceIDFromContext(ctx context.Context) string {")
	g.P("// 首先尝试从logv获取")
	g.P("if traceID := logv.GetTraceID(ctx); traceID != \"\" {")
	g.P("return traceID")
	g.P("}")
	g.P("// 然后尝试从context value获取")
	g.P("if tid := ctx.Value(\"trace_id\"); tid != nil {")
	g.P("if tidStr, ok := tid.(string); ok {")
	g.P("return tidStr")
	g.P("}")
	g.P("}")
	g.P("// 最后尝试从X-Trace-ID header获取（如果context中有headers）")
	g.P("if headers := ctx.Value(\"headers\"); headers != nil {")
	g.P("if headerMap, ok := headers.(map[string][]string); ok {")
	g.P("if traceHeaders, exists := headerMap[\"x-trace-id\"]; exists && len(traceHeaders) > 0 {")
	g.P("return traceHeaders[0]")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P("return \"\"")
	g.P("}")
	g.P()

	// HTTP方法处理函数
	generateHTTPMethodHandlers(g)
}

// generateHTTPMethodHandlers 生成HTTP方法处理函数
func generateHTTPMethodHandlers(g *protogen.GeneratedFile) {
	// HandleGET 方法
	g.P("// HandleGET 处理GET请求")
	g.P("func (h *", connectx.GlobalNames.DefaultHTTPMethodHandler, ") HandleGET(w http.ResponseWriter, r *http.Request, path string) error {")
	g.P("// GET请求通常用于查询，可以从URL参数中提取数据")
	g.P("query := r.URL.Query()")
	g.P()
	g.P("// 将GET参数转换为JSON格式的POST请求体")
	g.P("if len(query) > 0 {")
	g.P("// 创建一个新的POST请求")
	g.P("newReq := r.Clone(r.Context())")
	g.P("newReq.Method = \"POST\"")
	g.P("newReq.Header.Set(\"Content-Type\", \"application/json\")")
	g.P()
	g.P("// 将查询参数转换为JSON")
	g.P("jsonData := make(map[string]interface{})")
	g.P("for key, values := range query {")
	g.P("if len(values) == 1 {")
	g.P("jsonData[key] = values[0]")
	g.P("} else {")
	g.P("jsonData[key] = values")
	g.P("}")
	g.P("}")
	g.P()
	g.P("// 序列化为JSON")
	g.P("jsonBytes, err := json.Marshal(jsonData)")
	g.P("if err != nil {")
	g.P("http.Error(w, \"Invalid query parameters\", http.StatusBadRequest)")
	g.P("return err")
	g.P("}")
	g.P()
	g.P("// 设置请求体")
	g.P("newReq.Body = ", g.QualifiedGoIdent(connectx.IoPackage.Ident("NopCloser")), "(bytes.NewReader(jsonBytes))")
	g.P("newReq.ContentLength = int64(len(jsonBytes))")
	g.P()
	g.P("// 转发给Connect处理器")
	g.P("h.connectHandler.ServeHTTP(w, newReq)")
	g.P("return nil")
	g.P("}")
	g.P()
	g.P("// 如果没有查询参数，返回方法信息")
	g.P("w.Header().Set(\"Content-Type\", \"application/json\")")
	g.P("w.WriteHeader(http.StatusOK)")
	g.P("w.Write([]byte(`{\"message\":\"GET method supported\",\"path\":\"` + path + `\",\"usage\":\"Add query parameters for data\"}`))")
	g.P("return nil")
	g.P("}")
	g.P()

	// HandlePOST 方法
	g.P("// HandlePOST 处理POST请求")
	g.P("func (h *", connectx.GlobalNames.DefaultHTTPMethodHandler, ") HandlePOST(w http.ResponseWriter, r *http.Request, path string) error {")
	g.P("// POST请求直接转发给Connect处理器")
	g.P("h.connectHandler.ServeHTTP(w, r)")
	g.P("return nil")
	g.P("}")
	g.P()

	// HandleDELETE 方法
	g.P("// HandleDELETE 处理DELETE请求")
	g.P("func (h *", connectx.GlobalNames.DefaultHTTPMethodHandler, ") HandleDELETE(w http.ResponseWriter, r *http.Request, path string) error {")
	g.P("// DELETE请求可以从URL参数或请求体中获取数据")
	g.P("query := r.URL.Query()")
	g.P()
	g.P("// 创建一个新的POST请求来处理DELETE逻辑")
	g.P("newReq := r.Clone(r.Context())")
	g.P("newReq.Method = ", connectx.HTTPMethodPOST)
	g.P("newReq.Header.Set(\"Content-Type\", \"application/json\")")
	g.P("newReq.Header.Set(\"X-HTTP-Method-Override\", ", connectx.HTTPMethodDELETE, ")")
	g.P()
	g.P("// 如果有查询参数，转换为JSON")
	g.P("if len(query) > 0 {")
	g.P("jsonData := make(map[string]interface{})")
	g.P("for key, values := range query {")
	g.P("if len(values) == 1 {")
	g.P("jsonData[key] = values[0]")
	g.P("} else {")
	g.P("jsonData[key] = values")
	g.P("}")
	g.P("}")
	g.P()
	g.P("jsonBytes, err := json.Marshal(jsonData)")
	g.P("if err != nil {")
	g.P("http.Error(w, \"Invalid query parameters\", http.StatusBadRequest)")
	g.P("return err")
	g.P("}")
	g.P()
	g.P("newReq.Body = ", g.QualifiedGoIdent(connectx.IoPackage.Ident("NopCloser")), "(bytes.NewReader(jsonBytes))")
	g.P("newReq.ContentLength = int64(len(jsonBytes))")
	g.P("}")
	g.P()
	g.P("// 转发给Connect处理器")
	g.P("h.connectHandler.ServeHTTP(w, newReq)")
	g.P("return nil")
	g.P("}")
	g.P()

	// HandlePUT 方法
	g.P("// HandlePUT 处理PUT请求")
	g.P("func (h *", connectx.GlobalNames.DefaultHTTPMethodHandler, ") HandlePUT(w http.ResponseWriter, r *http.Request, path string) error {")
	g.P("// PUT请求类似POST，但添加方法覆盖头")
	g.P("newReq := r.Clone(r.Context())")
	g.P("newReq.Method = ", connectx.HTTPMethodPOST)
	g.P("newReq.Header.Set(\"X-HTTP-Method-Override\", ", connectx.HTTPMethodPUT, ")")
	g.P()
	g.P("// 转发给Connect处理器")
	g.P("h.connectHandler.ServeHTTP(w, newReq)")
	g.P("return nil")
	g.P("}")
	g.P()
}

// generateServiceChain 生成 ServiceChain 链式服务管理器
func generateServiceChain(g *protogen.GeneratedFile, file *protogen.File) {
	// MethodInfo 存储方法信息
	g.P("// MethodInfo 存储方法信息")
	g.P("type MethodInfo struct {")
	g.P("Name            string")
	g.P("ProcedurePath   string")
	g.P("SupportedMethods []string")
	g.P("}")
	g.P()

	// ServiceInfo 结构体用于存储服务信息
	g.P("// ServiceInfo 存储服务信息")
	g.P("type ServiceInfo struct {")
	g.P("ServiceName string")
	g.P("Methods     []MethodInfo")
	g.P("BasePath    string")
	g.P("}")
	g.P()

	// StartupHook 启动钩子函数类型
	g.P("// StartupHook 启动钩子函数类型")
	g.P("type StartupHook func() error")
	g.P()

	// CORSConfig CORS配置
	g.P("type CORSConfig struct {")
	g.P("AllowOrigins     []string")
	g.P("AllowMethods     []string")
	g.P("AllowHeaders     []string")
	g.P("ExposeHeaders    []string")
	g.P("AllowCredentials bool")
	g.P("MaxAge           int")
	g.P("}")
	g.P()

	// CustomRoute 自定义路由结构
	g.P("// CustomRoute 自定义路由结构")
	g.P("type CustomRoute struct {")
	g.P("Pattern     string")
	g.P("Handler     http.Handler")
	g.P("Method      string // 可选，指定HTTP方法")
	g.P("Description string // 路由描述/注释")
	g.P("}")
	g.P()

	// ServiceChain 结构体
	g.P("// ServiceChain 链式服务管理器")
	g.P("type ServiceChain struct {")
	g.P("mux              *http.ServeMux")
	g.P("interceptors     []Interceptor")
	g.P("port             string")
	g.P("services         []ServiceInfo")
	g.P("enableRequestLog bool")
	g.P("printAnnotations bool")
	g.P("startupHooks     []StartupHook")
	g.P("corsConfig       *CORSConfig")
	g.P("enableCORS       bool")
	g.P("customRoutes     []CustomRoute")
	g.P("enableTraceLog   bool // 启用trace日志")
	g.P("}")
	g.P()

	// DefaultCORSConfig 默认CORS配置
	g.P("func DefaultCORSConfig() *CORSConfig {")
	g.P("return &CORSConfig{")
	g.P("AllowOrigins:     []string{\"*\"},")
	g.P("AllowMethods:     []string{", connectx.HTTPMethodGET, ", ", connectx.HTTPMethodPOST, ", ", connectx.HTTPMethodPUT, ", ", connectx.HTTPMethodDELETE, ", ", connectx.HTTPMethodOPTIONS, ", ", connectx.HTTPMethodHEAD, ", ", connectx.HTTPMethodPATCH, "},")
	g.P("AllowHeaders:     []string{\"Content-Type\", \"Authorization\", \"X-Requested-With\", \"Accept\", \"Origin\", \"Access-Control-Request-Method\", \"Access-Control-Request-Headers\", \"x-token\"},")
	g.P("ExposeHeaders:    []string{\"Content-Length\", \"Access-Control-Allow-Origin\", \"Access-Control-Allow-Headers\", \"Content-Type\"},")
	g.P("AllowCredentials: true,")
	g.P("MaxAge:           86400, // 24小时")
	g.P("}")
	g.P("}")
	g.P()

	// NewServiceChain 构造函数
	g.P("// NewServiceChain 创建新的服务链")
	g.P("func NewServiceChain() *ServiceChain {")
	g.P("return &ServiceChain{")
	g.P("mux:              http.NewServeMux(),")
	g.P("interceptors:     []Interceptor{},")
	g.P("port:             \":8080\",")
	g.P("services:         []ServiceInfo{},")
	g.P("enableRequestLog: false,")
	g.P("printAnnotations: false,")
	g.P("startupHooks:     []StartupHook{},")
	g.P("corsConfig:       DefaultCORSConfig(),")
	g.P("enableCORS:       true, // 默认启用CORS")
	g.P("customRoutes:     []CustomRoute{},")
	g.P("enableTraceLog:   false, // 默认关闭trace日志")
	g.P("}")
	g.P("}")
	g.P()

	// CORS中间件函数
	g.P("// corsMiddleware CORS中间件")
	g.P("func (sc *ServiceChain) corsMiddleware(next http.Handler) http.Handler {")
	g.P("return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {")
	g.P("// 生成trace_id并添加到请求头和响应头")
	g.P("traceID := r.Header.Get(\"X-Trace-ID\")")
	g.P("if traceID == \"\" {")
	g.P("traceID = generateTraceID()")
	g.P("}")
	g.P("// 将trace_id添加到请求头")
	g.P("r.Header.Set(\"X-Trace-ID\", traceID)")
	g.P("// 将trace_id添加到响应头")
	g.P("w.Header().Set(\"X-Trace-ID\", traceID)")
	g.P("logv.SetLevel(zerolog.DebugLevel)")
	g.P("ctx := logv.WithNewTraceID(r.Context())")
	g.P("r = r.WithContext(ctx)")
	g.P()
	g.P("// 使用logv记录请求开始")
	g.P("if sc.enableTraceLog {")
	g.P("log.Info().Str(\"trace_id\", GetTraceIDFromContext(r.Context())).Str(\"method\", r.Method).Str(\"path\", r.URL.Path).Str(\"Path\", r.URL.Path).Str(\"remote_addr\", r.RemoteAddr).Msg(\"HTTP请求开始\")")
	g.P("}")
	g.P()
	g.P("if !sc.enableCORS {")
	g.P("next.ServeHTTP(w, r)")
	g.P("return")
	g.P("}")
	g.P()
	g.P("config := sc.corsConfig")
	g.P("origin := r.Header.Get(\"Origin\")")
	g.P()
	g.P("// 设置允许的源")
	g.P("if len(config.AllowOrigins) > 0 {")
	g.P("if config.AllowOrigins[0] == \"*\" {")
	g.P("w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")")
	g.P("} else {")
	g.P("for _, allowedOrigin := range config.AllowOrigins {")
	g.P("if origin == allowedOrigin {")
	g.P("w.Header().Set(\"Access-Control-Allow-Origin\", origin)")
	g.P("break")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P()
	g.P("// 设置允许的方法")
	g.P("if len(config.AllowMethods) > 0 {")
	g.P("w.Header().Set(\"Access-Control-Allow-Methods\", strings.Join(config.AllowMethods, \", \"))")
	g.P("}")
	g.P()
	g.P("// 设置允许的头部")
	g.P("if len(config.AllowHeaders) > 0 {")
	g.P("w.Header().Set(\"Access-Control-Allow-Headers\", strings.Join(config.AllowHeaders, \", \"))")
	g.P("}")
	g.P()
	g.P("// 设置暴露的头部")
	g.P("if len(config.ExposeHeaders) > 0 {")
	g.P("w.Header().Set(\"Access-Control-Expose-Headers\", strings.Join(config.ExposeHeaders, \", \"))")
	g.P("}")
	g.P()
	g.P("// 设置是否允许凭证")
	g.P("if config.AllowCredentials {")
	g.P("w.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")")
	g.P("}")
	g.P()
	g.P("// 设置预检请求缓存时间")
	g.P("if config.MaxAge > 0 {")
	g.P("w.Header().Set(\"Access-Control-Max-Age\", fmt.Sprintf(\"%d\", config.MaxAge))")
	g.P("}")
	g.P()
	g.P("// 处理预检请求")
	g.P("if r.Method == ", connectx.HTTPMethodOPTIONS, " {")
	g.P("if sc.enableTraceLog {")
	g.P("// logv.Info(\"处理OPTIONS预检请求\", \"trace_id\", traceID)")
	g.P("}")
	g.P("w.WriteHeader(http.StatusOK)")
	g.P("return")
	g.P("}")
	g.P()
	g.P("next.ServeHTTP(w, r)")
	g.P("})")
	g.P("}")
	g.P()

	// CORS配置方法
	g.P("// WithCORS 启用/禁用CORS")
	g.P("func (sc *ServiceChain) WithCORS(enable bool) *ServiceChain {")
	g.P("sc.enableCORS = enable")
	g.P("return sc")
	g.P("}")
	g.P()

	g.P("// WithCORSConfig 设置自定义CORS配置")
	g.P("func (sc *ServiceChain) WithCORSConfig(config *CORSConfig) *ServiceChain {")
	g.P("if config != nil {")
	g.P("sc.corsConfig = config")
	g.P("}")
	g.P("return sc")
	g.P("}")
	g.P()

	g.P("// WithCORSOrigins 设置允许的源")
	g.P("func (sc *ServiceChain) WithCORSOrigins(origins ...string) *ServiceChain {")
	g.P("sc.corsConfig.AllowOrigins = origins")
	g.P("return sc")
	g.P("}")
	g.P()

	g.P("// WithCORSMethods 设置允许的HTTP方法")
	g.P("func (sc *ServiceChain) WithCORSMethods(methods ...string) *ServiceChain {")
	g.P("sc.corsConfig.AllowMethods = methods")
	g.P("return sc")
	g.P("}")
	g.P()

	g.P("// WithCORSHeaders 设置允许的头部")
	g.P("func (sc *ServiceChain) WithCORSHeaders(headers ...string) *ServiceChain {")
	g.P("sc.corsConfig.AllowHeaders = headers")
	g.P("return sc")
	g.P("}")
	g.P()

	// WithInterceptors 方法
	g.P("// WithInterceptors 添加拦截器")
	g.P("func (sc *ServiceChain) WithInterceptors(interceptors ...Interceptor) *ServiceChain {")
	g.P("sc.interceptors = append(sc.interceptors, interceptors...)")
	g.P("return sc")
	g.P("}")
	g.P()

	// WithPort 方法
	g.P("// WithPort 设置端口")
	g.P("func (sc *ServiceChain) WithPort(port string) *ServiceChain {")
	g.P("sc.port = port")
	g.P("return sc")
	g.P("}")
	g.P()

	// WithRequestLog 方法
	g.P("// WithRequestLog 启用/禁用HTTP请求日志")
	g.P("func (sc *ServiceChain) WithRequestLog(enable bool) *ServiceChain {")
	g.P("sc.enableRequestLog = enable")
	g.P("return sc")
	g.P("}")
	g.P()

	// WithFieldAnnotations 方法
	g.P("// WithFieldAnnotations 启用/禁用字段注解打印")
	g.P("func (sc *ServiceChain) WithFieldAnnotations(enable bool) *ServiceChain {")
	g.P("sc.printAnnotations = enable")
	g.P("return sc")
	g.P("}")
	g.P()

	// WithTraceLog 方法
	g.P("// WithTraceLog 启用/禁用trace日志")
	g.P("func (sc *ServiceChain) WithTraceLog(enable bool) *ServiceChain {")
	g.P("sc.enableTraceLog = enable")
	g.P("return sc")
	g.P("}")
	g.P()

	// AddStartupHook 添加启动钩子
	g.P("// AddStartupHook 添加启动钩子函数")
	g.P("func (sc *ServiceChain) AddStartupHook(hook StartupHook) *ServiceChain {")
	g.P("sc.startupHooks = append(sc.startupHooks, hook)")
	g.P("return sc")
	g.P("}")
	g.P()

	// AddStartupHooks 批量添加启动钩子
	g.P("// AddStartupHooks 批量添加启动钩子函数")
	g.P("func (sc *ServiceChain) AddStartupHooks(hooks ...StartupHook) *ServiceChain {")
	g.P("sc.startupHooks = append(sc.startupHooks, hooks...)")
	g.P("return sc")
	g.P("}")
	g.P()

	// AddCustomRoute 添加自定义HTTP路由
	g.P("// AddCustomRoute 添加自定义HTTP路由")
	g.P("func (sc *ServiceChain) AddCustomRoute(pattern string, handler http.Handler) *ServiceChain {")
	g.P("sc.customRoutes = append(sc.customRoutes, CustomRoute{")
	g.P("Pattern: pattern,")
	g.P("Handler: handler,")
	g.P("})")
	g.P("return sc")
	g.P("}")
	g.P()

	// AddCustomRouteWithDescription 添加带注释的自定义HTTP路由
	g.P("// AddCustomRouteWithDescription 添加带注释的自定义HTTP路由")
	g.P("func (sc *ServiceChain) AddCustomRouteWithDescription(pattern string, handler http.Handler, description string) *ServiceChain {")
	g.P("sc.customRoutes = append(sc.customRoutes, CustomRoute{")
	g.P("Pattern:     pattern,")
	g.P("Handler:     handler,")
	g.P("Description: description,")
	g.P("})")
	g.P("return sc")
	g.P("}")
	g.P()

	// AddCustomRouteWithMethod 添加指定HTTP方法的自定义路由
	g.P("// AddCustomRouteWithMethod 添加指定HTTP方法的自定义路由")
	g.P("func (sc *ServiceChain) AddCustomRouteWithMethod(pattern string, method string, handler http.Handler) *ServiceChain {")
	g.P("sc.customRoutes = append(sc.customRoutes, CustomRoute{")
	g.P("Pattern: pattern,")
	g.P("Handler: handler,")
	g.P("Method:  method,")
	g.P("})")
	g.P("return sc")
	g.P("}")
	g.P()

	// AddCustomRouteWithMethodAndDescription 添加指定HTTP方法和注释的自定义路由
	g.P("// AddCustomRouteWithMethodAndDescription 添加指定HTTP方法和注释的自定义路由")
	g.P("func (sc *ServiceChain) AddCustomRouteWithMethodAndDescription(pattern string, method string, handler http.Handler, description string) *ServiceChain {")
	g.P("sc.customRoutes = append(sc.customRoutes, CustomRoute{")
	g.P("Pattern:     pattern,")
	g.P("Handler:     handler,")
	g.P("Method:      method,")
	g.P("Description: description,")
	g.P("})")
	g.P("return sc")
	g.P("}")
	g.P()

	// AddCustomHandlerFunc 添加自定义HandlerFunc路由
	g.P("// AddCustomHandlerFunc 添加自定义HandlerFunc路由")
	g.P("func (sc *ServiceChain) AddCustomHandlerFunc(pattern string, handlerFunc http.HandlerFunc) *ServiceChain {")
	g.P("return sc.AddCustomRoute(pattern, handlerFunc)")
	g.P("}")
	g.P()

	// AddCustomHandlerFuncWithDescription 添加带注释的自定义HandlerFunc路由
	g.P("// AddCustomHandlerFuncWithDescription 添加带注释的自定义HandlerFunc路由")
	g.P("func (sc *ServiceChain) AddCustomHandlerFuncWithDescription(pattern string, handlerFunc http.HandlerFunc, description string) *ServiceChain {")
	g.P("return sc.AddCustomRouteWithDescription(pattern, handlerFunc, description)")
	g.P("}")
	g.P()

	// AddRESTEndpoint 添加REST风格的端点")
	g.P("// AddRESTEndpoint 添加REST风格的端点")
	g.P("func (sc *ServiceChain) AddRESTEndpoint(basePath string, getHandler, postHandler, putHandler, deleteHandler http.Handler) *ServiceChain {")
	g.P("if getHandler != nil {")
	g.P("sc.AddCustomRouteWithMethod(basePath, ", connectx.HTTPMethodGET, ", getHandler)")
	g.P("}")
	g.P("if postHandler != nil {")
	g.P("sc.AddCustomRouteWithMethod(basePath, ", connectx.HTTPMethodPOST, ", postHandler)")
	g.P("}")
	g.P("if putHandler != nil {")
	g.P("sc.AddCustomRouteWithMethod(basePath, ", connectx.HTTPMethodPUT, ", putHandler)")
	g.P("}")
	g.P("if deleteHandler != nil {")
	g.P("sc.AddCustomRouteWithMethod(basePath, ", connectx.HTTPMethodDELETE, ", deleteHandler)")
	g.P("}")
	g.P("return sc")
	g.P("}")
	g.P()

	// AddRESTEndpointWithDescription 添加带注释的REST风格端点
	g.P("// AddRESTEndpointWithDescription 添加带注释的REST风格端点")
	g.P("func (sc *ServiceChain) AddRESTEndpointWithDescription(basePath string, description string, getHandler, postHandler, putHandler, deleteHandler http.Handler) *ServiceChain {")
	g.P("if getHandler != nil {")
	g.P("sc.AddCustomRouteWithMethodAndDescription(basePath, ", connectx.HTTPMethodGET, ", getHandler, description+\" - 获取资源\")")
	g.P("}")
	g.P("if postHandler != nil {")
	g.P("sc.AddCustomRouteWithMethodAndDescription(basePath, ", connectx.HTTPMethodPOST, ", postHandler, description+\" - 创建资源\")")
	g.P("}")
	g.P("if putHandler != nil {")
	g.P("sc.AddCustomRouteWithMethodAndDescription(basePath, ", connectx.HTTPMethodPUT, ", putHandler, description+\" - 更新资源\")")
	g.P("}")
	g.P("if deleteHandler != nil {")
	g.P("sc.AddCustomRouteWithMethodAndDescription(basePath, ", connectx.HTTPMethodDELETE, ", deleteHandler, description+\" - 删除资源\")")
	g.P("}")
	g.P("return sc")
	g.P("}")
	g.P()

	// printAllServices 方法
	g.P("// printAllServices 打印所有注册的服务和方法")
	g.P("func (sc *ServiceChain) printAllServices() {")
	g.P("fmt.Println(\"\\n📋 已注册的服务和方法:\")")
	g.P("for _, service := range sc.services {")
	g.P("for _, method := range service.Methods {")
	g.P("fmt.Printf(\"         🌐 路径: %s,支持的HTTP方法: %s\\n\", method.ProcedurePath, strings.Join(method.SupportedMethods, \", \"))")
	g.P("}")
	g.P("}")
	g.P()
	g.P("// 显示自定义路由")
	g.P("if len(sc.customRoutes) > 0 {")
	g.P("fmt.Println(\"\\n📍 自定义路由:\")")
	g.P("for _, route := range sc.customRoutes {")
	g.P("methodStr := \"ALL\"")
	g.P("if route.Method != \"\" {")
	g.P("methodStr = route.Method")
	g.P("}")
	g.P("if route.Description != \"\" {")
	g.P("fmt.Printf(\"         🌐 路径: %s,支持的HTTP方法: %s - %s\\n\", route.Pattern, methodStr, route.Description)")
	g.P("} else {")
	g.P("fmt.Printf(\"         🌐 路径: %s,支持的HTTP方法: %s\\n\", route.Pattern, methodStr)")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P()
	g.P("fmt.Printf(\"\\n🚀 服务器启动在: http://localhost%s\\n\\n\", sc.port)")
	g.P("}")
	g.P()

	// executeStartupHooks 执行启动钩子
	g.P("// executeStartupHooks 执行所有启动钩子")
	g.P("func (sc *ServiceChain) executeStartupHooks() error {")
	g.P("fmt.Println(\"\\n🔗 执行启动钩子...\")")
	g.P("for i, hook := range sc.startupHooks {")
	g.P("fmt.Printf(\"执行钩子 %d/%d...\\n\", i+1, len(sc.startupHooks))")
	g.P("if err := hook(); err != nil {")
	g.P("fmt.Printf(\"❌ 钩子 %d 执行失败: %v\\n\", i+1, err)")
	g.P("return fmt.Errorf(\"启动钩子 %d 执行失败: %w\", i+1, err)")
	g.P("}")
	g.P("fmt.Printf(\"✅ 钩子 %d 执行成功\\n\", i+1)")
	g.P("}")
	g.P("if len(sc.startupHooks) > 0 {")
	g.P("fmt.Printf(\"🎉 所有 %d 个启动钩子执行完成\\n\", len(sc.startupHooks))")
	g.P("}")
	g.P("return nil")
	g.P("}")
	g.P()

	// registerCustomRoutes 注册自定义路由
	g.P("// registerCustomRoutes 注册自定义路由")
	g.P("func (sc *ServiceChain) registerCustomRoutes() {")
	g.P("if len(sc.customRoutes) == 0 {")
	g.P("return")
	g.P("}")
	g.P()
	g.P("fmt.Println(\"\\n🔗 注册自定义路由:\")")
	g.P("for _, route := range sc.customRoutes {")
	g.P("if route.Method != \"\" {")
	g.P("// 带HTTP方法限制的路由")
	g.P("methodHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {")
	g.P("if r.Method != route.Method {")
	g.P("http.Error(w, fmt.Sprintf(\"Method %s not allowed, expected %s\", r.Method, route.Method), http.StatusMethodNotAllowed)")
	g.P("return")
	g.P("}")
	g.P("route.Handler.ServeHTTP(w, r)")
	g.P("})")
	g.P("finalHandler := sc.corsMiddleware(methodHandler)")
	g.P("sc.mux.Handle(route.Pattern, finalHandler)")
	g.P("if route.Description != \"\" {")
	g.P("fmt.Printf(\"  📍 %s [%s] -> %s\\n\", route.Pattern, route.Method, route.Description)")
	g.P("} else {")
	g.P("fmt.Printf(\"  📍 %s [%s] -> 自定义处理器\\n\", route.Pattern, route.Method)")
	g.P("}")
	g.P("} else {")
	g.P("// 不限制HTTP方法的路由")
	g.P("finalHandler := sc.corsMiddleware(route.Handler)")
	g.P("sc.mux.Handle(route.Pattern, finalHandler)")
	g.P("if route.Description != \"\" {")
	g.P("fmt.Printf(\"  📍 %s [ALL] -> %s\\n\", route.Pattern, route.Description)")
	g.P("} else {")
	g.P("fmt.Printf(\"  📍 %s [ALL] -> 自定义处理器\\n\", route.Pattern)")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P()

	// Start 方法
	g.P("// Start 启动服务器")
	g.P("func (sc *ServiceChain) Start() error {")
	g.P("// 执行启动钩子")
	g.P("if err := sc.executeStartupHooks(); err != nil {")
	g.P("return err")
	g.P("}")
	g.P()
	g.P("// 注册自定义路由")
	g.P("sc.registerCustomRoutes()")
	g.P()
	g.P("sc.printAllServices()")
	g.P("sc.printFieldAnnotations()")
	g.P("return http.ListenAndServe(sc.port, sc.mux)")
	g.P("}")
	g.P()

	// printFieldAnnotations 方法
	g.P("// printFieldAnnotations 打印所有服务的字段注解")
	g.P("func (sc *ServiceChain) printFieldAnnotations() {")
	g.P("if !sc.printAnnotations {")
	g.P("return")
	g.P("}")
	g.P("fmt.Println(\"\\n📝 所有服务字段注解信息:\")")
	g.P("fmt.Println(strings.Repeat(\"=\", 60))")
	g.P("for _, service := range sc.services {")
	g.P("fmt.Printf(\"\\n🔧 服务: %s\\n\", service.ServiceName)")
	g.P("for _, method := range service.Methods {")
	g.P("fmt.Printf(\"  📋 方法: %s\\n\", method.Name)")
	g.P("fmt.Printf(\"    🌐 路径: %s\\n\", method.ProcedurePath)")
	g.P("fmt.Printf(\"    📡 HTTP方法: %s\\n\", strings.Join(method.SupportedMethods, \", \"))")
	g.P("}")
	g.P("}")
	g.P("fmt.Println(strings.Repeat(\"=\", 60))")
	g.P("}")
	g.P()

	// logRequest 方法
	g.P("// logRequest 记录HTTP请求")
	g.P("func (sc *ServiceChain) logRequest(r *http.Request) {")
	g.P("if !sc.enableRequestLog {")
	g.P("return")
	g.P("}")
	g.P("fmt.Printf(\"[%s] 📡 %s %s - %s\\n\", ")
	g.P("time.Now().Format(\"2006-01-02 15:04:05\"),")
	g.P("r.Method,")
	g.P("r.URL.Path,")
	g.P("r.RemoteAddr)")
	g.P("}")
	g.P()

	// WithHomePage 方法
	g.P("func (sc *ServiceChain) WithHomePage(addr ...string) *ServiceChain {")
	g.P("defaultAddr := \"index.html\"")
	g.P("if len(addr) > 0 && addr[0] != \"\" {")
	g.P("defaultAddr = addr[0]")
	g.P("}")
	g.P("// 动态生成主页内容")
	g.P("sc.mux.HandleFunc(\"/\"+defaultAddr, func(w http.ResponseWriter, r *http.Request) {")
	g.P("w.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")")
	g.P("fmt.Fprint(w, `<!DOCTYPE html>")
	g.P("<html>")
	g.P("<head>")
	g.P("<title>文档地址</title>")
	g.P("<style>")
	g.P("body { font-family: Arial, sans-serif; margin: 20px; }")
	g.P(".method { margin: 10px 0; padding: 10px; border: 1px solid #ddd; border-radius: 5px; }")
	g.P(".http-methods { color: #666; font-size: 0.9em; }")
	g.P("</style>")
	g.P("</head>")
	g.P("<body>")
	g.P("<h1>🧪 测试链式服务</h1>`)")
	g.P()
	g.P("// 动态生成服务链接")
	g.P("for _, service := range sc.services {")
	g.P("fmt.Fprintf(w, `<h2>🔧 %s</h2>`, service.ServiceName)")
	g.P("fmt.Fprintf(w, `<p><strong>路径:</strong> %s</p>`, service.BasePath)")
	g.P("for _, method := range service.Methods {")
	g.P("fmt.Fprint(w, `<div class=\"method\">`)")
	g.P("fmt.Fprintf(w, `<h3>%s</h3>`, method.Name)")
	g.P("fmt.Fprintf(w, `<p><strong>路径:</strong> %s</p>`, method.ProcedurePath)")
	g.P("fmt.Fprintf(w, `<p class=\"http-methods\"><strong>支持的HTTP方法:</strong> %s</p>`, strings.Join(method.SupportedMethods, \", \"))")
	g.P("// 为每种支持的HTTP方法生成测试链接")
	g.P("fmt.Fprint(w, `<p><strong>测试链接:</strong> `)")
	g.P("for i, httpMethod := range method.SupportedMethods {")
	g.P("if i > 0 {")
	g.P("fmt.Fprint(w, ` | `)")
	g.P("}")
	g.P("if httpMethod == ", connectx.HTTPMethodGET, " {")
	g.P("fmt.Fprintf(w, `<a href=\"%s?name=Test\" target=\"_blank\">%s</a>`, method.ProcedurePath, httpMethod)")
	g.P("} else {")
	g.P("fmt.Fprintf(w, `<span>%s (需要工具测试)</span>`, httpMethod)")
	g.P("}")
	g.P("}")
	g.P("fmt.Fprint(w, `</p>`)")
	g.P("fmt.Fprint(w, `</div>`)")
	g.P("}")
	g.P("}")
	g.P()
	g.P("fmt.Fprint(w, `</body></html>`)")
	g.P("})")
	g.P()
	g.P("return sc")
	g.P("}")
	g.P()
}

// generateServiceChainMethod 生成服务链注册方法
func generateServiceChainMethod(g *protogen.GeneratedFile, service *protogen.Service) {
	serviceName := service.GoName
	serverInterface := serviceName + "Server"
	handlerFunc := "New" + serviceName + "HandlerWithMethodConfig"

	g.P("// ", serviceName, " 添加", serviceName, "服务")
	g.P("func (sc *ServiceChain) ", serviceName, "(server ", serverInterface, ", methodConfigs []MethodHTTPConfig) *ServiceChain {")
	g.P("// 检查服务器接口实现")
	g.P("if err := Validate", serviceName, "ServerImplementation(server); err != nil {")
	g.P("panic(fmt.Sprintf(\"❌ ", serviceName, "服务接口实现检查失败: %v\", err))")
	g.P("}")
	g.P()
	g.P("path, handler := ", handlerFunc, "(server, sc.interceptors, methodConfigs)")
	g.P("// 包装handler以添加请求日志和CORS支持")
	g.P("wrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {")
	g.P("sc.logRequest(r)")
	g.P("handler.ServeHTTP(w, r)")
	g.P("})")
	g.P("// 应用CORS中间件")
	g.P("finalHandler := sc.corsMiddleware(wrappedHandler)")
	g.P("sc.mux.Handle(path, finalHandler)")
	g.P()

	// 构建方法配置映射
	g.P("// 构建方法配置映射")
	g.P("methodConfigMap := make(map[string][]string)")
	g.P("for _, config := range methodConfigs {")
	g.P("methodConfigMap[config.MethodName] = config.AllowedMethods")
	g.P("}")
	g.P()

	// 收集服务方法信息
	g.P("// 收集服务方法信息")
	g.P("methods := []MethodInfo{")
	for _, method := range service.Methods {
		procedureName := serviceName + method.GoName + "Procedure"
		g.P("{")
		g.P("Name: \"", method.GoName, "\",")
		g.P("ProcedurePath: ", procedureName, ",")
		g.P("SupportedMethods: func() []string {")
		g.P("if configMethods, exists := methodConfigMap[\"", method.GoName, "\"]; exists {")
		g.P("return configMethods")
		g.P("} else {")
		g.P("return []string{", connectx.HTTPMethodPOST, "} // 默认只支持POST")
		g.P("}")
		g.P("}(),")
		g.P("},")
	}
	g.P("}")
	g.P()

	g.P("// 添加到服务列表")
	g.P("sc.services = append(sc.services, ServiceInfo{")
	g.P("ServiceName: \"", serviceName, "\",")
	g.P("Methods:     methods,")
	g.P("BasePath:    path,")
	g.P("})")
	g.P()

	g.P("fmt.Printf(\"✅ 已注册 ", serviceName, " 服务: %s\\n\", path)")
	g.P("return sc")
	g.P("}")
	g.P()
}

// generateTraceIDCode 生成 trace ID 相关代码
func generateTraceIDCode(g *protogen.GeneratedFile) {
	g.P("// 全局变量存储当前的 context，用于全局日志钩子")
	g.P("var (")
	g.P("globalCtx   context.Context")
	g.P("globalMutex sync.RWMutex")
	g.P(")")
	g.P()

	g.P("// TraceIDHook 是一个 zerolog 钩子，自动为所有日志添加 trace ID")
	g.P("type TraceIDHook struct {")
	g.P("ctx context.Context")
	g.P("}")
	g.P()

	g.P("// NewTraceIDHook 创建一个新的 TraceID 钩子")
	g.P("func NewTraceIDHook(ctx context.Context) *TraceIDHook {")
	g.P("return &TraceIDHook{ctx: ctx}")
	g.P("}")
	g.P()

	g.P("// Run 实现 zerolog.Hook 接口")
	g.P("func (h *TraceIDHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {")
	g.P("if h.ctx != nil {")
	g.P("traceID := GetTraceIDFromContext(h.ctx)")
	g.P("if traceID != \"\" {")
	g.P("e.Str(\"trace_id\", traceID)")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P()

	g.P("// LoggerWithTraceID 返回一个带有 trace ID 钩子的日志器")
	g.P("func LoggerWithTraceID(ctx context.Context) *zerolog.Logger {")
	g.P("hook := NewTraceIDHook(ctx)")
	g.P("logger := log.Hook(hook)")
	g.P("return &logger")
	g.P("}")
	g.P()

	g.P("// Info 返回一个自动包含 trace ID 的 Info 级别日志事件")
	g.P("func Info(ctx context.Context) *zerolog.Event {")
	g.P("logger := LoggerWithTraceID(ctx)")
	g.P("return logger.Info()")
	g.P("}")
	g.P()

	g.P("// Debug 返回一个自动包含 trace ID 的 Debug 级别日志事件")
	g.P("func Debug(ctx context.Context) *zerolog.Event {")
	g.P("logger := LoggerWithTraceID(ctx)")
	g.P("return logger.Debug()")
	g.P("}")
	g.P()

	g.P("// Error 返回一个自动包含 trace ID 的 Error 级别日志事件")
	g.P("func Error(ctx context.Context) *zerolog.Event {")
	g.P("logger := LoggerWithTraceID(ctx)")
	g.P("return logger.Error()")
	g.P("}")
	g.P()

	g.P("// Warn 返回一个自动包含 trace ID 的 Warn 级别日志事件")
	g.P("func Warn(ctx context.Context) *zerolog.Event {")
	g.P("logger := LoggerWithTraceID(ctx)")
	g.P("return logger.Warn()")
	g.P("}")
	g.P()

	g.P("// Fatal 返回一个自动包含 trace ID 的 Fatal 级别日志事件")
	g.P("func Fatal(ctx context.Context) *zerolog.Event {")
	g.P("logger := LoggerWithTraceID(ctx)")
	g.P("return logger.Fatal()")
	g.P("}")
	g.P()

	g.P("// Panic 返回一个自动包含 trace ID 的 Panic 级别日志事件")
	g.P("func Panic(ctx context.Context) *zerolog.Event {")
	g.P("logger := LoggerWithTraceID(ctx)")
	g.P("return logger.Panic()")
	g.P("}")
	g.P()

	g.P("// SetGlobalContext 设置全局 context，用于全局日志钩子")
	g.P("func SetGlobalContext(ctx context.Context) {")
	g.P("globalMutex.Lock()")
	g.P("defer globalMutex.Unlock()")
	g.P("globalCtx = ctx")
	g.P("}")
	g.P()

	g.P("// GetGlobalContext 获取全局 context")
	g.P("func GetGlobalContext() context.Context {")
	g.P("globalMutex.RLock()")
	g.P("defer globalMutex.RUnlock()")
	g.P("return globalCtx")
	g.P("}")
	g.P()

	g.P("// GlobalTraceIDHook 全局 trace ID 钩子")
	g.P("type GlobalTraceIDHook struct{}")
	g.P()

	g.P("// Run 实现 zerolog.Hook 接口，从全局 context 中获取 trace_id")
	g.P("func (h *GlobalTraceIDHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {")
	g.P("ctx := GetGlobalContext()")
	g.P("if ctx != nil {")
	g.P("traceID := GetTraceIDFromContext(ctx)")
	g.P("if traceID != \"\" {")
	g.P("e.Str(\"trace_id\", traceID)")
	g.P("}")
	g.P("}")
	g.P("}")
	g.P()

	g.P("// InitGlobalTraceIDHook 初始化全局 trace ID 钩子")
	g.P("func InitGlobalTraceIDHook() {")
	g.P("hook := &GlobalTraceIDHook{}")
	g.P("log.Logger = log.Hook(hook)")
	g.P("}")
	g.P()
}

// generateService 生成服务相关的额外方法（如果需要的话）
func generateService(g *protogen.GeneratedFile, file *protogen.File) {
	// 这个函数现在为空，避免重复生成 ServiceChain
	// 如果将来需要生成其他服务相关的代码，可以在这里添加
}
